home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / GCC 1.37.1r14 / usr / gcc-1.37.1r14 / non-obj files / ld.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-10-01  |  130.8 KB  |  4,894 lines  |  [TEXT/CPED]

  1. #define fatal ld_fatal
  2. #define error ld_error
  3. #define progname ld_progname
  4.  
  5. /* Linker `ld' for GNU
  6.    Copyright (C) 1988 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 1, or (at your option)
  11.    any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* Written by Richard Stallman with some help from Eric Albert.
  23.    Set, indirect, and warning symbol features added by Randy Smith.  */
  24.    
  25. /* Define how to initialize system-dependent header fields.  */
  26. #ifdef sun
  27. /* Use Sun's TARGET convention.  */
  28. #ifndef TARGET
  29. #define SUN2 2
  30. #define SUN3 3
  31. #define SUN4 4
  32. #if defined(sparc)
  33. #define TARGET SUN4
  34. #else
  35. #if defined(mc68020) || defined(m68020)
  36. #define TARGET SUN3
  37. #else
  38. #define TARGET SUN2
  39. #endif
  40. #endif
  41. #else
  42. #define _CROSS_TARGET_ARCH TARGET  /* locate the correct a.out.h file */
  43. #endif
  44. #endif
  45.  
  46. #include <ar.h>
  47. #include <stdio.h>
  48. #include <sys/types.h>
  49. #include <sys/stat.h>
  50. #include <sys/file.h>
  51. #include <sys/time.h>
  52. #include <sys/resource.h>
  53. #ifndef sony_news
  54. #include <fcntl.h>
  55. #endif
  56.  
  57. #ifdef COFF_ENCAPSULATE
  58. #include "a.out.encap.h"
  59. #else
  60. #include <a.out.h>
  61. #endif
  62.  
  63. #ifndef N_SET_MAGIC
  64. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  65. #endif
  66.  
  67. /* If compiled with GNU C, use the built-in alloca */
  68. #ifdef __GNUC__
  69. #define alloca __builtin_alloca
  70. #endif
  71.  
  72. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  73.  
  74. #include "stab.h"
  75. #define CORE_ADDR unsigned long    /* For symseg.h */
  76. #include "symseg.h"
  77.  
  78. #ifdef USG
  79. #include <string.h>
  80. #else
  81. #include <strings.h>
  82. #endif
  83.  
  84. /* Determine whether we should attempt to handle (minimally)
  85.    N_BINCL and N_EINCL.  */
  86.  
  87. #if defined (__GNU_STAB__) || defined (N_BINCL)
  88. #define HAVE_SUN_STABS
  89. #endif
  90.  
  91. #define min(a,b) ((a) < (b) ? (a) : (b))
  92.  
  93. /* Macro to control the number of undefined references printed */
  94. #define MAX_UREFS_PRINTED    10
  95.  
  96. /* Size of a page; obtained from the operating system.  */
  97.  
  98. int page_size;
  99.  
  100. /* Name this program was invoked by.  */
  101.  
  102. char *progname;
  103.  
  104. /* System dependencies */
  105.  
  106. /* Define this if names etext, edata and end should not start with `_'.  */
  107. /* #define nounderscore 1 */
  108.  
  109. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  110.    whose native format is different.  */
  111. /* #define NON_NATIVE */
  112.  
  113. /* Define this to specify the default executable format.  */
  114.  
  115. #ifdef hpux
  116. #define DEFAULT_MAGIC NMAGIC  /* hpux bugs screw ZMAGIC */
  117. #endif
  118.  
  119. #ifndef DEFAULT_MAGIC
  120. #define DEFAULT_MAGIC ZMAGIC
  121. #endif
  122.  
  123. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  124.  
  125. #ifndef N_TXTADDR
  126. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  127. #define N_TXTADDR(X) 0
  128. #endif
  129. #ifdef is68k
  130. #define N_TXTADDR(x)  (sizeof (struct exec))
  131. #endif
  132. #ifdef sequent
  133. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  134. #endif
  135. #endif
  136.  
  137. #ifndef N_DATADDR
  138. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  139. #define N_DATADDR(x) \
  140.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  141.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  142. #endif
  143. #ifdef is68k
  144. #define SEGMENT_SIZE 0x20000
  145. #define N_DATADDR(x) \
  146. (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  147.  : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  148. #endif
  149. #ifdef sequent
  150. #define N_DATADDR(x) \
  151.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  152.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  153. #endif
  154. #endif
  155.  
  156. #ifdef sun
  157. #if TARGET == SUN4
  158. #define INITIALIZE_HEADER \
  159. {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  160. #endif
  161. #if TARGET == SUN2
  162. #define INITIALIZE_HEADER outheader.a_machtype = M_68010
  163. #endif
  164. #ifndef INITIALIZE_HEADER
  165. #define INITIALIZE_HEADER outheader.a_machtype = M_68020
  166. #endif
  167. #define TEXT_START(x) N_PAGSIZ(x)
  168. #endif
  169. #ifdef ALTOS
  170. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  171. #endif
  172. #ifdef is68k
  173. #ifdef M_68020
  174. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  175.    a_machtype field and so won't recognize the magic number.  To keep
  176.    binary compatibility for now, just ignore it */
  177. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  178. #endif
  179. #endif
  180. #ifdef hpux
  181. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  182. #endif
  183. #if defined(i386) && !defined(sequent)
  184. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  185. #endif
  186.  
  187. #ifdef is68k
  188. /* This enables code to take care of an ugly hack in the ISI OS.
  189.    If a symbol beings with _$, then the object file is included only
  190.    if the rest of the symbol name has been referenced. */
  191. #define DOLLAR_KLUDGE
  192. #endif
  193.  
  194. /*
  195.  * Alloca include.
  196.  */
  197. #if defined(sun) && defined(sparc) && !defined(__GNUC__)
  198. #include "alloca.h"
  199. #endif
  200.  
  201. #ifndef L_SET
  202. #define L_SET 0
  203. #endif
  204.  
  205. /*
  206.  * Ok.  Following are the relocation information macros.  If your
  207.  * system should not be able to use the default set (below), you must
  208.  * define the following:
  209.  
  210.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  211.  * of structure that is stored in the relocation info section of your
  212.  * a.out files.  Often this is defined in the a.out.h for your system.
  213.  *
  214.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  215.  * <whatever> to be relocated.  *Must be an lvalue*.
  216.  *
  217.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  218.  * external symbol (1), or was it fully resolved upon entering the
  219.  * loader (0) in which case some combination of the value in memory
  220.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  221.  * what the value of the relocation actually was.  *Must be an lvalue*.
  222.  *
  223.  *   RELOC_TYPE (rval): If this entry was fully resolved upon
  224.  * entering the loader, what type should it be relocated as?
  225.  *
  226.  *   RELOC_SYMBOL (rval): If this entry was not fully resolved upon
  227.  * entering the loader, what is the index of it's symbol in the symbol
  228.  * table?  *Must be a lvalue*.
  229.  *
  230.  *   RELOC_MEMORY_ADD_P (rval): This should return true if the final
  231.  * relocation value output here should be added to memory, or if the
  232.  * section of memory described should simply be set to the relocation
  233.  * value.
  234.  *
  235.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  236.  * an extra value to be added to the relocation value based on the
  237.  * individual relocation entry.  *Must be an lvalue if defined*.
  238.  *
  239.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  240.  * pc relative.
  241.  *
  242.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  243.  * final relocation value before putting it where it belongs.
  244.  *
  245.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  246.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  247.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  248.  * do everything in terms of the bit operators below), but having this
  249.  * macro could end up producing better code on machines without fancy
  250.  * bit twiddling.  Also, it's easier to understand/code big/little
  251.  * endian distinctions with this macro.
  252.  *
  253.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  254.  * object described in RELOC_TARGET_SIZE in which the relocation value
  255.  * will go.
  256.  *
  257.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  258.  * with the bits of the relocation value.  It may be assumed by the
  259.  * code that the relocation value will fit into this many bits.  This
  260.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  261.  *
  262.  *
  263.  *        Things I haven't implemented
  264.  *        ----------------------------
  265.  *
  266.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  267.  *
  268.  *    Pc relative relocation for External references.
  269.  *
  270.  *
  271.  */
  272. #ifndef THINK_C
  273. /* The following #if has been modifed for cross compilation */
  274. /* It originally read:  #if defined(sun) && defined(sparc)  */
  275. /* Marc Ullman, Stanford University    Nov. 1 1989  */
  276. #if defined(sun) && (TARGET == SUN4)
  277. /* Sparc (Sun 4) macros */
  278. #undef relocation_info
  279. #define relocation_info                    reloc_info_sparc
  280. #define RELOC_ADDRESS(r)        ((r)->r_address)
  281. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  282. #define RELOC_TYPE(r)                   ((r)->r_index)
  283. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  284. #define RELOC_MEMORY_SUB_P(r)        0
  285. #define RELOC_MEMORY_ADD_P(r)           0
  286. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  287. #define RELOC_PCREL_P(r)             \
  288.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  289. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  290. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  291. #define RELOC_TARGET_BITPOS(r)          0
  292. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  293. #endif
  294.  
  295. /* Note that these are very dependent on the order of the enums in
  296.    enum reloc_type (in a.out.h); if they change the following must be
  297.    changed */
  298. /* Also note that the last few may be incorrect; I have no information */
  299. static int reloc_target_rightshift[] = {
  300.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  301. };
  302. static int reloc_target_size[] = {
  303.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  304. };
  305. static int reloc_target_bitsize[] = {
  306.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  307. };
  308.  
  309. #define    MAX_ALIGNMENT    (sizeof (double))
  310. #endif
  311. #ifdef sequent
  312. #define RELOC_ADDRESS(r)        ((r)->r_address)
  313. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  314. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  315. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  316. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  317. #define RELOC_MEMORY_ADD_P(r)    1
  318. #undef RELOC_ADD_EXTRA
  319. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  320. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  321. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  322. #define RELOC_TARGET_BITPOS(r)    0
  323. #define RELOC_TARGET_BITSIZE(r)    32
  324. #endif
  325.  
  326. /* Default macros */
  327. #ifndef RELOC_ADDRESS
  328. #define RELOC_ADDRESS(r)        ((r)->r_address)
  329. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  330. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  331. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  332. #define RELOC_MEMORY_SUB_P(r)    0
  333. #define RELOC_MEMORY_ADD_P(r)    1
  334. #undef RELOC_ADD_EXTRA
  335. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  336. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  337. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  338. #define RELOC_TARGET_BITPOS(r)    0
  339. #define RELOC_TARGET_BITSIZE(r)    32
  340. #endif
  341.  
  342. #ifndef MAX_ALIGNMENT
  343. #define    MAX_ALIGNMENT    (sizeof (int))
  344. #endif
  345.  
  346. #ifdef nounderscore
  347. #define LPREFIX '.'
  348. #else
  349. #define LPREFIX 'L'
  350. #endif
  351.  
  352. #ifndef TEXT_START
  353. #define TEXT_START(x) N_TXTADDR(x)
  354. #endif
  355.  
  356. /* Special global symbol types understood by GNU LD.  */
  357.  
  358. /* The following type indicates the definition of a symbol as being
  359.    an indirect reference to another symbol.  The other symbol
  360.    appears as an undefined reference, immediately following this symbol.
  361.  
  362.    Indirection is asymmetrical.  The other symbol's value will be used
  363.    to satisfy requests for the indirect symbol, but not vice versa.
  364.    If the other symbol does not have a definition, libraries will
  365.    be searched to find a definition.
  366.  
  367.    So, for example, the following two lines placed in an assembler
  368.    input file would result in an object file which would direct gnu ld
  369.    to resolve all references to symbol "foo" as references to symbol
  370.    "bar".
  371.  
  372.     .stabs "_foo",11,0,0,0
  373.     .stabs "_bar",1,0,0,0
  374.  
  375.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  376.  
  377. #ifndef N_INDR
  378. #define N_INDR 0xa
  379. #endif
  380.  
  381. /* The following symbols refer to set elements.  These are expected
  382.    only in input to the loader; they should not appear in loader
  383.    output (unless relocatable output is requested).  To be recognized
  384.    by the loader, the input symbols must have their N_EXT bit set.
  385.    All the N_SET[ATDB] symbols with the same name form one set.  The
  386.    loader collects all of these elements at load time and outputs a
  387.    vector for each name.
  388.    Space (an array of 32 bit words) is allocated for the set in the
  389.    data section, and the n_value field of each set element value is
  390.    stored into one word of the array.
  391.    The first word of the array is the length of the set (number of
  392.    elements).  The last word of the vector is set to zero for possible
  393.    use by incremental loaders.  The array is ordered by the linkage
  394.    order; the first symbols which the linker encounters will be first
  395.    in the array.
  396.  
  397.    In C syntax this looks like:
  398.  
  399.     struct set_vector {
  400.       unsigned int length;
  401.       unsigned int vector[length];
  402.       unsigned int always_zero;
  403.     };
  404.  
  405.    Before being placed into the array, each element is relocated
  406.    according to its type.  This allows the loader to create an array
  407.    of pointers to objects automatically.  N_SETA type symbols will not
  408.    be relocated.
  409.  
  410.    The address of the set is made into an N_SETV symbol
  411.    whose name is the same as the name of the set.
  412.    This symbol acts like a N_DATA global symbol
  413.    in that it can satisfy undefined external references.
  414.  
  415.    For the purposes of determining whether or not to load in a library
  416.    file, set element definitions are not considered "real
  417.    definitions"; they will not cause the loading of a library
  418.    member.
  419.  
  420.    If relocatable output is requested, none of this processing is
  421.    done.  The symbols are simply relocated and passed through to the
  422.    output file.
  423.  
  424.    So, for example, the following three lines of assembler code
  425.    (whether in one file or scattered between several different ones)
  426.    will produce a three element vector (total length is five words;
  427.    see above), referenced by the symbol "_xyzzy", which will have the
  428.    addresses of the routines _init1, _init2, and _init3.
  429.  
  430.    *NOTE*: If symbolic addresses are used in the n_value field of the
  431.    defining .stabs, those symbols must be defined in the same file as
  432.    that containing the .stabs.
  433.  
  434.     .stabs "_xyzzy",23,0,0,_init1
  435.     .stabs "_xyzzy",23,0,0,_init2
  436.     .stabs "_xyzzy",23,0,0,_init3
  437.  
  438.    Note that (23 == (N_SETT | N_EXT)).  */
  439.  
  440. #ifndef N_SETA
  441. #define    N_SETA    0x14        /* Absolute set element symbol */
  442. #endif                /* This is input to LD, in a .o file.  */
  443.  
  444. #ifndef N_SETT
  445. #define    N_SETT    0x16        /* Text set element symbol */
  446. #endif                /* This is input to LD, in a .o file.  */
  447.  
  448. #ifndef N_SETD
  449. #define    N_SETD    0x18        /* Data set element symbol */
  450. #endif                /* This is input to LD, in a .o file.  */
  451.  
  452. #ifndef N_SETB
  453. #define    N_SETB    0x1A        /* Bss set element symbol */
  454. #endif                /* This is input to LD, in a .o file.  */
  455.  
  456. /* Macros dealing with the set element symbols defined in a.out.h */
  457. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  458. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  459.  
  460. #ifndef N_SETV
  461. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  462. #endif                /* This is output from LD.  */
  463.  
  464. /* If a this type of symbol is encountered, its name is a warning
  465.    message to print each time the symbol referenced by the next symbol
  466.    table entry is referenced.
  467.  
  468.    This feature may be used to allow backwards compatibility with
  469.    certain functions (eg. gets) but to discourage programmers from
  470.    their use.
  471.  
  472.    So if, for example, you wanted to have ld print a warning whenever
  473.    the function "gets" was used in their C program, you would add the
  474.    following to the assembler file in which gets is defined:
  475.  
  476.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  477.     .stabs "_gets",1,0,0,0
  478.  
  479.    These .stabs do not necessarily have to be in the same file as the
  480.    gets function, they simply must exist somewhere in the compilation.  */
  481.  
  482. #ifndef N_WARNING
  483. #define N_WARNING 0x1E        /* Warning message to print if symbol
  484.                    included */
  485. #endif                /* This is input to ld */
  486.  
  487. #ifndef __GNU_STAB__
  488.  
  489. /* Line number for the data section.  This is to be used to describe
  490.    the source location of a variable declaration.  */
  491. #ifndef N_DSLINE
  492. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  493. #endif
  494.  
  495. /* Line number for the bss section.  This is to be used to describe
  496.    the source location of a variable declaration.  */
  497. #ifndef N_BSLINE
  498. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  499. #endif
  500.  
  501. #endif /* not __GNU_STAB__ */
  502.  
  503. /* Symbol table */
  504.  
  505. /* Global symbol data is recorded in these structures,
  506.    one for each global symbol.
  507.    They are found via hashing in 'symtab', which points to a vector of buckets.
  508.    Each bucket is a chain of these structures through the link field.  */
  509.  
  510. typedef
  511.   struct glosym
  512.     {
  513.       /* Pointer to next symbol in this symbol's hash bucket.  */
  514.       struct glosym *link;
  515.       /* Name of this symbol.  */
  516.       char *name;
  517.       /* Value of this symbol as a global symbol.  */
  518.       long value;
  519.       /* Chain of external 'nlist's in files for this symbol, both defs
  520.      and refs.  */
  521.       struct nlist *refs;
  522.       /* Any warning message that might be associated with this symbol
  523.          from an N_WARNING symbol encountered. */
  524.       char *warning;
  525.       /* Nonzero means definitions of this symbol as common have been seen,
  526.      and the value here is the largest size specified by any of them.  */
  527.       int max_common_size;
  528.       /* For relocatable_output, records the index of this global sym in the
  529.      symbol table to be written, with the first global sym given index 0.*/
  530.       int def_count;
  531.       /* Nonzero means a definition of this global symbol is known to exist.
  532.      Library members should not be loaded on its account.  */
  533.       char defined;
  534.       /* Nonzero means a reference to this global symbol has been seen
  535.      in a file that is surely being loaded.
  536.      A value higher than 1 is the n_type code for the symbol's
  537.      definition.  */
  538.       char referenced;
  539.       /* A count of the number of undefined references printed for a
  540.      specific symbol.  If a symbol is unresolved at the end of
  541.      digest_symbols (and the loading run is supposed to produce
  542.      relocatable output) do_file_warnings keeps track of how many
  543.      unresolved reference error messages have been printed for
  544.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  545.      messages stop. */
  546.       unsigned char undef_refs;
  547.       /* 1 means that this symbol has multiple definitions.  2 means
  548.          that it has multiple definitions, and some of them are set
  549.      elements, one of which has been printed out already.  */
  550.       unsigned char multiply_defined;
  551.       /* Nonzero means print a message at all refs or defs of this symbol */
  552.       char trace;
  553.     }
  554.   glosym;
  555.  
  556. /* Demangler for C++. */
  557. extern char *cplus_demangle ();
  558.  
  559. /* Demangler function to use. */
  560. char *(*demangler)() = NULL;
  561.  
  562. /* Number of buckets in glosym hash table */
  563. #define    TABSIZE    1009
  564.  
  565. /* The glosym hash table: a vector of TABSIZE pointers to struct glosym. */
  566. glosym *symtab[TABSIZE];
  567.  
  568. /* Number of symbols in glosym hash table. */
  569. int num_hash_tab_syms = 0;
  570.  
  571. /* Count the number of nlist entries that are for local symbols.
  572.    This count and the three following counts
  573.    are incremented as as symbols are entered in the glosym table.  */
  574. int local_sym_count;
  575.  
  576. /* Count number of nlist entries that are for local symbols
  577.    whose names don't start with L. */
  578. int non_L_local_sym_count;
  579.  
  580. /* Count the number of nlist entries for debugger info.  */
  581. int debugger_sym_count;
  582.  
  583. /* Count the number of global symbols referenced and not defined.  */
  584. int undefined_global_sym_count;
  585.  
  586. /* Count the number of global symbols multiply defined.  */
  587. int multiple_def_count;
  588.  
  589. /* Count the number of defined global symbols.
  590.    Each symbol is counted only once
  591.    regardless of how many different nlist entries refer to it,
  592.    since the output file will need only one nlist entry for it.
  593.    This count is computed by `digest_symbols';
  594.    it is undefined while symbols are being loaded. */
  595. int defined_global_sym_count;
  596.  
  597. /* Count the number of symbols defined through common declarations.
  598.    This count is kept in symdef_library, linear_library, and
  599.    enter_global_ref.  It is incremented when the defined flag is set
  600.    in a symbol because of a common definition, and decremented when
  601.    the symbol is defined "for real" (ie. by something besides a common
  602.    definition).  */
  603. int common_defined_global_count;
  604.  
  605. /* Count the number of set element type symbols and the number of
  606.    separate vectors which these symbols will fit into.  See the
  607.    GNU a.out.h for more info.
  608.    This count is computed by 'enter_file_symbols' */
  609. int set_symbol_count;
  610. int set_vector_count;
  611.  
  612. /* Define a linked list of strings which define symbols which should
  613.    be treated as set elements even though they aren't.  Any symbol
  614.    with a prefix matching one of these should be treated as a set
  615.    element.
  616.  
  617.    This is to make up for deficiencies in many assemblers which aren't
  618.    willing to pass any stabs through to the loader which they don't
  619.    understand.  */
  620. struct string_list_element {
  621.   char *str;
  622.   struct string_list_element *next;
  623. };
  624.  
  625. struct string_list_element *set_element_prefixes;
  626.  
  627. /* Count the number of definitions done indirectly (ie. done relative
  628.    to the value of some other symbol. */
  629. int global_indirect_count;
  630.  
  631. /* Count the number of warning symbols encountered. */
  632. int warning_count;
  633.  
  634. /* Total number of symbols to be written in the output file.
  635.    Computed by digest_symbols from the variables above.  */
  636. int nsyms;
  637.  
  638.  
  639. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  640.    -e sets this.  */
  641. glosym *entry_symbol;
  642.  
  643. glosym *edata_symbol;   /* the symbol _edata */
  644. glosym *etext_symbol;   /* the symbol _etext */
  645. glosym *end_symbol;    /* the symbol _end */
  646.  
  647. /* Each input file, and each library member ("subfile") being loaded,
  648.    has a `file_entry' structure for it.
  649.  
  650.    For files specified by command args, these are contained in the vector
  651.    which `file_table' points to.
  652.  
  653.    For library members, they are dynamically allocated,
  654.    and chained through the `chain' field.
  655.    The chain is found in the `subfiles' field of the `file_entry'.
  656.    The `file_entry' objects for the members have `superfile' fields pointing
  657.    to the one for the library.  */
  658.  
  659. struct file_entry {
  660.   /* Name of this file.  */
  661.   char *filename;
  662.   /* Name to use for the symbol giving address of text start */
  663.   /* Usually the same as filename, but for a file spec'd with -l
  664.      this is the -l switch itself rather than the filename.  */
  665.   char *local_sym_name;
  666.  
  667.   /* Describe the layout of the contents of the file */
  668.  
  669.   /* The file's a.out header.  */
  670.   struct exec header;
  671.   /* Offset in file of GDB symbol segment, or 0 if there is none.  */
  672.   int symseg_offset;
  673.  
  674.   /* Describe data from the file loaded into core */
  675.  
  676.   /* Symbol table of the file.  */
  677.   struct nlist *symbols;
  678.   /* Size in bytes of string table.  */
  679.   int string_size;
  680.   /* Pointer to the string table.
  681.      The string table is not kept in core all the time,
  682.      but when it is in core, its address is here.  */
  683.   char *strings;
  684.  
  685.   /* Next two used only if `relocatable_output' or if needed for */
  686.   /* output of undefined reference line numbers. */
  687.  
  688.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  689.   struct relocation_info *textrel;
  690.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  691.   struct relocation_info *datarel;
  692.  
  693.   /* Relation of this file's segments to the output file */
  694.  
  695.   /* Start of this file's text seg in the output file core image.  */
  696.   int text_start_address;
  697.   /* Start of this file's data seg in the output file core image.  */
  698.   int data_start_address;
  699.   /* Start of this file's bss seg in the output file core image.  */
  700.   int bss_start_address;
  701.   /* Offset in bytes in the output file symbol table
  702.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  703.   int local_syms_offset;
  704.  
  705.   /* For library members only */
  706.  
  707.   /* For a library, points to chain of entries for the library members.  */
  708.   struct file_entry *subfiles;
  709.   /* For a library member, offset of the member within the archive.
  710.      Zero for files that are not library members.  */
  711.   int starting_offset;
  712.   /* Size of contents of this file, if library member.  */
  713.   int total_size;
  714.   /* For library member, points to the library's own entry.  */
  715.   struct file_entry *superfile;
  716.   /* For library member, points to next entry for next member.  */
  717.   struct file_entry *chain;
  718.  
  719.   /* 1 if file is a library. */
  720.   char library_flag;
  721.  
  722.   /* 1 if file's header has been read into this structure.  */
  723.   char header_read_flag;
  724.  
  725.   /* 1 means search a set of directories for this file.  */
  726.   char search_dirs_flag;
  727.  
  728.   /* 1 means this is base file of incremental load.
  729.      Do not load this file's text or data.
  730.      Also default text_start to after this file's bss. */
  731.   char just_syms_flag;
  732. };
  733.  
  734. /* Vector of entries for input files specified by arguments.
  735.    These are all the input files except for members of specified libraries.  */
  736. struct file_entry *file_table;
  737.  
  738. /* Length of that vector.  */
  739. int number_of_files;
  740.  
  741. /* When loading the text and data, we can avoid doing a close
  742.    and another open between members of the same library.
  743.  
  744.    These two variables remember the file that is currently open.
  745.    Both are zero if no file is open.
  746.  
  747.    See `each_file' and `file_close'.  */
  748.  
  749. struct file_entry *input_file;
  750. int input_desc;
  751.  
  752. /* The name of the file to write; "a.out" by default.  */
  753.  
  754. char *output_filename;
  755.  
  756. /* Descriptor for writing that file with `mywrite'.  */
  757.  
  758. int outdesc;
  759.  
  760. /* Header for that file (filled in by `write_header').  */
  761.  
  762. struct exec outheader;
  763.  
  764. #ifdef COFF_ENCAPSULATE
  765. struct coffheader coffheader;
  766. int need_coff_header;
  767. #endif
  768.  
  769. /* The following are computed by `digest_symbols'.  */
  770.  
  771. int text_size;        /* total size of text of all input files.  */
  772. int data_size;        /* total size of data of all input files.  */
  773. int bss_size;        /* total size of bss of all input files.  */
  774. int text_reloc_size;    /* total size of text relocation of all input files.  */
  775. int data_reloc_size;    /* total size of data relocation of all input */
  776.             /* files.  */
  777.  
  778. /* Specifications of start and length of the area reserved at the end
  779.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  780. int set_sect_start;
  781. int set_sect_size;
  782.  
  783. /* Pointer for in core storage for the above vectors, before they are
  784.    written. */
  785. unsigned long *set_vectors;
  786.  
  787. /* Amount of cleared space to leave between the text and data segments.  */
  788.  
  789. int text_pad;
  790.  
  791. /* Amount of bss segment to include as part of the data segment.  */
  792.  
  793. int data_pad;
  794.  
  795. /* Format of __.SYMDEF:
  796.    First, a longword containing the size of the 'symdef' data that follows.
  797.    Second, zero or more 'symdef' structures.
  798.    Third, a longword containing the length of symbol name strings.
  799.    Fourth, zero or more symbol name strings (each followed by a null).  */
  800.  
  801. struct symdef {
  802.   int symbol_name_string_index;
  803.   int library_member_offset;
  804. };
  805.  
  806. /* Record most of the command options.  */
  807.  
  808. /* Address we assume the text section will be loaded at.
  809.    We relocate symbols and text and data for this, but we do not
  810.    write any padding in the output file for it.  */
  811. int text_start;
  812.  
  813. /* Offset of default entry-pc within the text section.  */
  814. int entry_offset;
  815.  
  816. /* Address we decide the data section will be loaded at.  */
  817. int data_start;
  818.  
  819. /* `text-start' address is normally this much plus a page boundary.
  820.    This is not a user option; it is fixed for each system.  */
  821. int text_start_alignment;
  822.  
  823. /* Nonzero if -T was specified in the command line.
  824.    This prevents text_start from being set later to default values.  */
  825. int T_flag_specified;
  826.  
  827. /* Nonzero if -Tdata was specified in the command line.
  828.    This prevents data_start from being set later to default values.  */
  829. int Tdata_flag_specified;
  830.  
  831. /* Size to pad data section up to.
  832.    We simply increase the size of the data section, padding with zeros,
  833.    and reduce the size of the bss section to match.  */
  834. int specified_data_size;
  835.  
  836. /* Magic number to use for the output file, set by switch.  */
  837. int magic;
  838.  
  839. /* Nonzero means print names of input files as processed.  */
  840. int trace_files;
  841.  
  842. /* Which symbols should be stripped (omitted from the output):
  843.    none, all, or debugger symbols.  */
  844. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  845.  
  846. /* Which local symbols should be omitted:
  847.    none, all, or those starting with L.
  848.    This is irrelevant if STRIP_NONE.  */
  849. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  850.  
  851. /* 1 => write load map.  */
  852. int write_map;
  853.  
  854. /* 1 => write relocation into output file so can re-input it later.  */
  855. int relocatable_output;
  856.  
  857. /* 1 => assign space to common symbols even if `relocatable_output'.  */
  858. int force_common_definition;
  859.  
  860. /* Standard directories to search for files specified by -l.  */
  861. char *standard_search_dirs[] =
  862. #ifdef STANDARD_SEARCH_DIRS
  863.   {STANDARD_SEARCH_DIRS};
  864. #else
  865. #ifdef NON_NATIVE
  866.   {"/usr/local/lib/gnu"};
  867. #else
  868.   {"/lib", "/usr/lib", "/usr/local/lib"};
  869. #endif
  870. #endif
  871.  
  872. /* Actual vector of directories to search;
  873.    this contains those specified with -L plus the standard ones.  */
  874. char **search_dirs;
  875.  
  876. /* Length of the vector `search_dirs'.  */
  877. int n_search_dirs;
  878.  
  879. /* Non zero means to create the output executable. */
  880. /* Cleared by nonfatal errors.  */
  881. int make_executable;
  882.  
  883. /* Force the executable to be output, even if there are non-fatal
  884.    errors */
  885. int force_executable;
  886.  
  887. /* Keep a list of any symbols referenced from the command line (so
  888.    that error messages for these guys can be generated). This list is
  889.    zero terminated. */
  890. struct glosym **cmdline_references;
  891. int cl_refs_allocated;
  892.  
  893. void bcopy (), bzero ();
  894.  
  895. void fatal ();
  896. void fatal_with_file ();
  897. void perror_name ();
  898. void perror_file ();
  899. void error ();
  900.  
  901. void digest_symbols ();
  902. void print_symbols ();
  903. void load_symbols ();
  904. void decode_command ();
  905. void list_undefined_symbols ();
  906. void list_unresolved_references ();
  907. void write_output ();
  908. void write_header ();
  909. void write_text ();
  910. void read_file_relocation ();
  911. void write_data ();
  912. void write_rel ();
  913. void write_syms ();
  914. void write_symsegs ();
  915. void mywrite ();
  916. void symtab_init ();
  917. void padfile ();
  918. char *concat ();
  919. char *get_file_name ();
  920. glosym *getsym (), *getsym_soft ();
  921.  
  922. int
  923. ld_main (argc, argv)
  924.      char **argv;
  925.      int argc;
  926. {
  927. /*   Added this to stop ld core-dumping on very large .o files.    */
  928. #ifdef RLIMIT_STACK
  929.   /* Get rid of any avoidable limit on stack size.  */
  930.   {
  931.     struct rlimit rlim;
  932.  
  933.     /* Set the stack limit huge so that alloca does not fail. */
  934.     getrlimit (RLIMIT_STACK, &rlim);
  935.     rlim.rlim_cur = rlim.rlim_max;
  936.     setrlimit (RLIMIT_STACK, &rlim);
  937.   }
  938. #endif /* RLIMIT_STACK */
  939.  
  940.   /* initialise data seg */
  941.   init_ld();
  942.  
  943.   page_size = getpagesize ();
  944.   progname = argv[0];
  945.  
  946.   /* Clear the cumulative info on the output file.  */
  947.  
  948.   text_size = 0;
  949.   data_size = 0;
  950.   bss_size = 0;
  951.   text_reloc_size = 0;
  952.   data_reloc_size = 0;
  953.  
  954.   data_pad = 0;
  955.   text_pad = 0;
  956.  
  957.   /* Initialize the data about options.  */
  958.  
  959.   specified_data_size = 0;
  960.   strip_symbols = STRIP_NONE;
  961.   trace_files = 0;
  962.   discard_locals = DISCARD_NONE;
  963.   entry_symbol = 0;
  964.   write_map = 0;
  965.   relocatable_output = 0;
  966.   force_common_definition = 0;
  967.   T_flag_specified = 0;
  968.   Tdata_flag_specified = 0;
  969.   magic = DEFAULT_MAGIC;
  970.   make_executable = 1;
  971.   force_executable = 0;
  972.   set_element_prefixes = 0;
  973.  
  974.   /* Initialize the cumulative counts of symbols.  */
  975.  
  976.   local_sym_count = 0;
  977.   non_L_local_sym_count = 0;
  978.   debugger_sym_count = 0;
  979.   undefined_global_sym_count = 0;
  980.   set_symbol_count = 0;
  981.   set_vector_count = 0;
  982.   global_indirect_count = 0;
  983.   warning_count = 0;
  984.   multiple_def_count = 0;
  985.   common_defined_global_count = 0;
  986.  
  987.   /* Keep a list of symbols referenced from the command line */
  988.   cl_refs_allocated = 10;
  989.   cmdline_references
  990.     = (struct glosym **) xmalloc (cl_refs_allocated
  991.                   * sizeof(struct glosym *));
  992.   *cmdline_references = 0;
  993.  
  994.   /* Completely decode ARGV.  */
  995.  
  996.   decode_command (argc, argv);
  997.  
  998.   /* Create the symbols `etext', `edata' and `end'.  */
  999.  
  1000.   if (!relocatable_output)
  1001.     symtab_init ();
  1002.  
  1003.   /* Determine whether to count the header as part of
  1004.      the text size, and initialize the text size accordingly.
  1005.      This depends on the kind of system and on the output format selected.  */
  1006.  
  1007.   N_SET_MAGIC (outheader, magic);
  1008. #ifdef INITIALIZE_HEADER
  1009.   INITIALIZE_HEADER;
  1010. #endif
  1011.  
  1012.   text_size = sizeof (struct exec);
  1013. #ifdef COFF_ENCAPSULATE
  1014.   if (relocatable_output == 0 && file_table[0].just_syms_flag == 0)
  1015.     {
  1016.       need_coff_header = 1;
  1017.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  1018.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  1019.       text_size += sizeof (struct coffheader);
  1020.     }
  1021. #endif
  1022.  
  1023.   text_size -= N_TXTOFF (outheader);
  1024.  
  1025.   if (text_size < 0)
  1026.     text_size = 0;
  1027.   entry_offset = text_size;
  1028.  
  1029.   if (!T_flag_specified && !relocatable_output)
  1030.     text_start = TEXT_START (outheader);
  1031.  
  1032.   /* The text-start address is normally this far past a page boundary.  */
  1033.   text_start_alignment = text_start % page_size;
  1034.  
  1035.   /* Load symbols of all input files.
  1036.      Also search all libraries and decide which library members to load.  */
  1037.  
  1038.   load_symbols ();
  1039.  
  1040.   /* Compute where each file's sections go, and relocate symbols.  */
  1041.  
  1042.   digest_symbols ();
  1043.  
  1044.   /* Print error messages for any missing symbols, for any warning
  1045.      symbols, and possibly multiple definitions */
  1046.  
  1047.   do_warnings (stderr);
  1048.  
  1049.   /* Print a map, if requested.  */
  1050.  
  1051.   if (write_map) print_symbols (stdout);
  1052.  
  1053.   /* Write the output file.  */
  1054.  
  1055.   write_output ();
  1056.  
  1057.   exit (!make_executable);
  1058. }
  1059.  
  1060. void decode_option ();
  1061.  
  1062. /* Analyze a command line argument.
  1063.    Return 0 if the argument is a filename.
  1064.    Return 1 if the argument is a option complete in itself.
  1065.    Return 2 if the argument is a option which uses an argument.
  1066.  
  1067.    Thus, the value is the number of consecutive arguments
  1068.    that are part of options.  */
  1069.  
  1070. int
  1071. classify_arg (arg)
  1072.      register char *arg;
  1073. {
  1074.   if (*arg != '-') return 0;
  1075.   switch (arg[1])
  1076.     {
  1077.     case 'A':
  1078.     case 'D':
  1079.     case 'e':
  1080.     case 'L':
  1081.     case 'l':
  1082.     case 'o':
  1083.     case 'u':
  1084.     case 'V':
  1085.     case 'y':
  1086.       if (arg[2])
  1087.     return 1;
  1088.       return 2;
  1089.  
  1090.     case 'B':
  1091.       if (! strcmp (&arg[2], "static"))
  1092.     return 1;
  1093.  
  1094.     case 'T':
  1095.       if (arg[2] == 0)
  1096.     return 2;
  1097.       if (! strcmp (&arg[2], "text"))
  1098.     return 2;
  1099.       if (! strcmp (&arg[2], "data"))
  1100.     return 2;
  1101.       return 1;
  1102.     }
  1103.  
  1104.   return 1;
  1105. }
  1106.  
  1107. /* Process the command arguments,
  1108.    setting up file_table with an entry for each input file,
  1109.    and setting variables according to the options.  */
  1110.  
  1111. void
  1112. decode_command (argc, argv)
  1113.      char **argv;
  1114.      int argc;
  1115. {
  1116.   register int i;
  1117.   register struct file_entry *p;
  1118.  
  1119.   number_of_files = 0;
  1120.   output_filename = "a.out";
  1121.  
  1122.   n_search_dirs = 0;
  1123.   search_dirs = (char **) xmalloc (sizeof (char *));
  1124.  
  1125.   /* First compute number_of_files so we know how long to make file_table.  */
  1126.   /* Also process most options completely.  */
  1127.  
  1128.   for (i = 1; i < argc; i++)
  1129.     {
  1130.       register int code = classify_arg (argv[i]);
  1131.       if (code)
  1132.     {
  1133.       if (i + code > argc)
  1134.         fatal ("no argument following %s\n", argv[i]);
  1135.  
  1136.       decode_option (argv[i], argv[i+1]);
  1137.  
  1138.       if (argv[i][1] == 'l' || argv[i][1] == 'A')
  1139.         number_of_files++;
  1140.  
  1141.       i += code - 1;
  1142.     }
  1143.       else
  1144.     number_of_files++;
  1145.     }
  1146.  
  1147.   if (!number_of_files)
  1148.     fatal ("no input files", 0);
  1149.  
  1150.   p = file_table
  1151.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1152.   bzero (p, number_of_files * sizeof (struct file_entry));
  1153.  
  1154.   /* Now scan again and fill in file_table.  */
  1155.   /* All options except -A and -l are ignored here.  */
  1156.  
  1157.   for (i = 1; i < argc; i++)
  1158.     {
  1159.       register int code = classify_arg (argv[i]);
  1160.  
  1161.       if (code)
  1162.     {
  1163.       char *string;
  1164.       if (code == 2)
  1165.         string = argv[i+1];
  1166.       else
  1167.         string = &argv[i][2];
  1168.  
  1169.       if (argv[i][1] == 'A')
  1170.         {
  1171.           if (p != file_table)
  1172.         fatal ("-A specified before an input file other than the first");
  1173.  
  1174.           p->filename = string;
  1175.           p->local_sym_name = string;
  1176.           p->just_syms_flag = 1;
  1177.           p++;
  1178.         }
  1179.       if (argv[i][1] == 'l')
  1180.         {
  1181.           p->filename = concat ("lib", string, ".a");
  1182.           p->local_sym_name = concat ("-l", string, "");
  1183.           p->search_dirs_flag = 1;
  1184.           p++;
  1185.         }
  1186.       i += code - 1;
  1187.     }
  1188.       else
  1189.     {
  1190.       p->filename = argv[i];
  1191.       p->local_sym_name = argv[i];
  1192.       p++;
  1193.     }
  1194.     }
  1195.  
  1196.   /* Now check some option settings for consistency.  */
  1197.  
  1198. #ifdef NMAGIC
  1199.   if ((magic == ZMAGIC || magic == NMAGIC)
  1200. #else
  1201.   if ((magic == ZMAGIC)
  1202. #endif
  1203.       && (text_start - text_start_alignment) & (page_size - 1))
  1204.     fatal ("-T argument not multiple of page size, with sharable output", 0);
  1205.  
  1206.   /* Append the standard search directories to the user-specified ones.  */
  1207.   {
  1208.     int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1209.     n_search_dirs += n;
  1210.     search_dirs
  1211.       = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1212.     bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1213.        n * sizeof (char *));
  1214.   }
  1215. }
  1216.  
  1217.  
  1218. void
  1219. add_cmdline_ref (sp)
  1220.      struct glosym *sp;
  1221. {
  1222.   struct glosym **ptr;
  1223.  
  1224.   for (ptr = cmdline_references;
  1225.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1226.        ptr++)
  1227.     ;
  1228.  
  1229.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1230.     {
  1231.       int diff = ptr - cmdline_references;
  1232.  
  1233.       cl_refs_allocated *= 2;
  1234.       cmdline_references = (struct glosym **)
  1235.     xrealloc (cmdline_references,
  1236.          cl_refs_allocated * sizeof (struct glosym *));
  1237.       ptr = cmdline_references + diff;
  1238.     }
  1239.  
  1240.   *ptr++ = sp;
  1241.   *ptr = (struct glosym *) 0;
  1242. }
  1243.  
  1244. int
  1245. set_element_prefixed_p (name)
  1246.      char *name;
  1247. {
  1248.   struct string_list_element *p;
  1249.   int i;
  1250.  
  1251.   for (p = set_element_prefixes; p; p = p->next)
  1252.     {
  1253.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1254.     ;
  1255.  
  1256.       if (p->str[i] == '\0')
  1257.     return 1;
  1258.     }
  1259.   return 0;
  1260. }
  1261.  
  1262. int ld_parse ();
  1263.  
  1264. /* Record an option and arrange to act on it later.
  1265.    ARG should be the following command argument,
  1266.    which may or may not be used by this option.
  1267.  
  1268.    The `l' and `A' options are ignored here since they actually
  1269.    specify input files.  */
  1270.  
  1271. void
  1272. decode_option (swt, arg)
  1273.      register char *swt, *arg;
  1274. {
  1275.   /* We get Bstatic from gcc on suns.  */
  1276.   if (! strcmp (swt + 1, "Bstatic"))
  1277.     return;
  1278.   if (! strcmp (swt + 1, "Ttext"))
  1279.     {
  1280.       text_start = ld_parse (arg, "%x", "invalid argument to -Ttext");
  1281.       T_flag_specified = 1;
  1282.       return;
  1283.     }
  1284.   if (! strcmp (swt + 1, "Tdata"))
  1285.     {
  1286.       data_start = ld_parse (arg, "%x", "invalid argument to -Tdata");
  1287.       Tdata_flag_specified = 1;
  1288.       return;
  1289.     }
  1290.   if (! strcmp (swt + 1, "noinhibit-exec"))
  1291.     {
  1292.       force_executable = 1;
  1293.       return;
  1294.     }
  1295.  
  1296.   if (swt[2] != 0)
  1297.     arg = &swt[2];
  1298.  
  1299.   switch (swt[1])
  1300.     {
  1301.     case 'A':
  1302.       return;
  1303.  
  1304.     case 'D':
  1305.       specified_data_size = ld_parse (arg, "%x", "invalid argument to -D");
  1306.       return;
  1307.  
  1308.     case 'd':
  1309.       force_common_definition = 1;
  1310.       return;
  1311.  
  1312.     case 'e':
  1313.       entry_symbol = getsym (arg);
  1314.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1315.     undefined_global_sym_count++;
  1316.       entry_symbol->referenced = 1;
  1317.       add_cmdline_ref (entry_symbol);
  1318.       return;
  1319.  
  1320.     case 'l':
  1321.       /* If linking with libg++, use the C++ demangler. */
  1322.       if (arg != NULL && strcmp (arg, "g++") == 0)
  1323.     demangler = cplus_demangle;
  1324.       return;
  1325.  
  1326.     case 'L':
  1327.       n_search_dirs++;
  1328.       search_dirs
  1329.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1330.       search_dirs[n_search_dirs - 1] = arg;
  1331.       return;
  1332.  
  1333.     case 'M':
  1334.       write_map = 1;
  1335.       return;
  1336.  
  1337.     case 'N':
  1338.       magic = OMAGIC;
  1339.       return;
  1340.  
  1341. #ifdef NMAGIC
  1342.     case 'n':
  1343.       magic = NMAGIC;
  1344.       return;
  1345. #endif
  1346.  
  1347.     case 'o':
  1348.       output_filename = arg;
  1349.       return;
  1350.  
  1351.     case 'r':
  1352.       relocatable_output = 1;
  1353.       magic = OMAGIC;
  1354.       text_start = 0;
  1355.       return;
  1356.  
  1357.     case 'S':
  1358.       strip_symbols = STRIP_DEBUGGER;
  1359.       return;
  1360.  
  1361.     case 's':
  1362.       strip_symbols = STRIP_ALL;
  1363.       return;
  1364.  
  1365.     case 'T':
  1366.       text_start = ld_parse (arg, "%x", "invalid argument to -T");
  1367.       T_flag_specified = 1;
  1368.       return;
  1369.  
  1370.     case 't':
  1371.       trace_files = 1;
  1372.       return;
  1373.  
  1374.     case 'u':
  1375.       {
  1376.     register glosym *sp = getsym (arg);
  1377.     if (!sp->defined && !sp->referenced)
  1378.       undefined_global_sym_count++;
  1379.     sp->referenced = 1;
  1380.     add_cmdline_ref (sp);
  1381.       }
  1382.       return;
  1383.  
  1384.     case 'V':
  1385.       {
  1386.     struct string_list_element *new
  1387.       = (struct string_list_element *)
  1388.         xmalloc (sizeof (struct string_list_element));
  1389.  
  1390.     new->str = arg;
  1391.     new->next = set_element_prefixes;
  1392.     set_element_prefixes = new;
  1393.     return;
  1394.       }
  1395.  
  1396.     case 'X':
  1397.       discard_locals = DISCARD_L;
  1398.       return;
  1399.  
  1400.     case 'x':
  1401.       discard_locals = DISCARD_ALL;
  1402.       return;
  1403.  
  1404.     case 'y':
  1405.       {
  1406.     register glosym *sp = getsym (&swt[2]);
  1407.     sp->trace = 1;
  1408.       }
  1409.       return;
  1410.  
  1411.     case 'z':
  1412.       magic = ZMAGIC;
  1413.       return;
  1414.  
  1415.     default:
  1416.       fatal ("invalid command option `%s'", swt);
  1417.     }
  1418. }
  1419.  
  1420. /** Convenient functions for operating on one or all files being */
  1421.  /** loaded.  */
  1422. void print_file_name ();
  1423.  
  1424. /* Call FUNCTION on each input file entry.
  1425.    Do not call for entries for libraries;
  1426.    instead, call once for each library member that is being loaded.
  1427.  
  1428.    FUNCTION receives two arguments: the entry, and ARG.  */
  1429.  
  1430. void
  1431. each_file (function, arg)
  1432.      register void (*function)();
  1433.      register int arg;
  1434. {
  1435.   register int i;
  1436.  
  1437.   for (i = 0; i < number_of_files; i++)
  1438.     {
  1439.       register struct file_entry *entry = &file_table[i];
  1440.       if (entry->library_flag)
  1441.         {
  1442.       register struct file_entry *subentry = entry->subfiles;
  1443.       for (; subentry; subentry = subentry->chain)
  1444.         (*function) (subentry, arg);
  1445.     }
  1446.       else
  1447.     (*function) (entry, arg);
  1448.     }
  1449. }
  1450.  
  1451. /* Call FUNCTION on each input file entry until it returns a non-zero
  1452.    value.  Return this value.
  1453.    Do not call for entries for libraries;
  1454.    instead, call once for each library member that is being loaded.
  1455.  
  1456.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1457.    function returning unsigned long (though this can probably be fudged). */
  1458.  
  1459. unsigned long
  1460. check_each_file (function, arg)
  1461.      register unsigned long (*function)();
  1462.      register int arg;
  1463. {
  1464.   register int i;
  1465.   register unsigned long return_val;
  1466.  
  1467.   for (i = 0; i < number_of_files; i++)
  1468.     {
  1469.       register struct file_entry *entry = &file_table[i];
  1470.       if (entry->library_flag)
  1471.         {
  1472.       register struct file_entry *subentry = entry->subfiles;
  1473.       for (; subentry; subentry = subentry->chain)
  1474.         if (return_val = (*function) (subentry, arg))
  1475.           return return_val;
  1476.     }
  1477.       else
  1478.     if (return_val = (*function) (entry, arg))
  1479.       return return_val;
  1480.     }
  1481.   return 0;
  1482. }
  1483.  
  1484. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1485.  
  1486. void
  1487. each_full_file (function, arg)
  1488.      register void (*function)();
  1489.      register int arg;
  1490. {
  1491.   register int i;
  1492.  
  1493.   for (i = 0; i < number_of_files; i++)
  1494.     {
  1495.       register struct file_entry *entry = &file_table[i];
  1496.       if (entry->just_syms_flag)
  1497.     continue;
  1498.       if (entry->library_flag)
  1499.         {
  1500.       register struct file_entry *subentry = entry->subfiles;
  1501.       for (; subentry; subentry = subentry->chain)
  1502.         (*function) (subentry, arg);
  1503.     }
  1504.       else
  1505.     (*function) (entry, arg);
  1506.     }
  1507. }
  1508.  
  1509. /* Close the input file that is now open.  */
  1510.  
  1511. void
  1512. file_close ()
  1513. {
  1514.   close (input_desc);
  1515.   input_desc = 0;
  1516.   input_file = 0;
  1517. }
  1518.  
  1519. /* Open the input file specified by 'entry', and return a descriptor.
  1520.    The open file is remembered; if the same file is opened twice in a row,
  1521.    a new open is not actually done.  */
  1522.  
  1523. int
  1524. file_open (entry)
  1525.      register struct file_entry *entry;
  1526. {
  1527.   register int desc;
  1528.  
  1529.   if (entry->superfile)
  1530.     return file_open (entry->superfile);
  1531.  
  1532.   if (entry == input_file)
  1533.     return input_desc;
  1534.  
  1535.   if (input_file) file_close ();
  1536.  
  1537.   if (entry->search_dirs_flag)
  1538.     {
  1539.       int i;
  1540.  
  1541.       for (i = 0; i < n_search_dirs; i++)
  1542.     {
  1543.       register char *string
  1544.         = concat (search_dirs[i], "/", entry->filename);
  1545.       desc = open (string, O_RDONLY, 0);
  1546.       if (desc > 0)
  1547.         {
  1548.           entry->filename = string;
  1549.           entry->search_dirs_flag = 0;
  1550.           break;
  1551.         }
  1552.       free (string);
  1553.     }
  1554.     }
  1555.   else
  1556.     desc = open (entry->filename, O_RDONLY, 0);
  1557.  
  1558.   if (desc > 0)
  1559.     {
  1560.       input_file = entry;
  1561.       input_desc = desc;
  1562.       return desc;
  1563.     }
  1564.  
  1565.   perror_file (entry);
  1566.   /* NOTREACHED */
  1567. }
  1568.  
  1569. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1570.    and then a newline.  */
  1571.  
  1572. void
  1573. prline_file_name (entry, outfile)
  1574.      struct file_entry *entry;
  1575.      FILE *outfile;
  1576. {
  1577.   print_file_name (entry, outfile);
  1578.   fprintf (outfile, "\n");
  1579. }
  1580.  
  1581. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1582.  
  1583. void
  1584. print_file_name (entry, outfile)
  1585.      struct file_entry *entry;
  1586.      FILE *outfile;
  1587. {
  1588.   if (entry->superfile)
  1589.     {
  1590.       print_file_name (entry->superfile, outfile);
  1591.       fprintf (outfile, "(%s)", entry->filename);
  1592.     }
  1593.   else
  1594.     fprintf (outfile, "%s", entry->filename);
  1595. }
  1596.  
  1597. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1598.  
  1599. char *
  1600. get_file_name (entry)
  1601.      struct file_entry *entry;
  1602. {
  1603.   char *result, *supfile;
  1604.   if (entry->superfile)
  1605.     {
  1606.       supfile = get_file_name (entry->superfile);
  1607.       result = (char *) xmalloc (strlen (supfile)
  1608.                  + strlen (entry->filename) + 3);
  1609.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1610.       free (supfile);
  1611.     }
  1612.   else
  1613.     {
  1614.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1615.       strcpy (result, entry->filename);
  1616.     }
  1617.   return result;
  1618. }
  1619.  
  1620. /* Medium-level input routines for rel files.  */
  1621.  
  1622. /* Read a file's header into the proper place in the file_entry.
  1623.    DESC is the descriptor on which the file is open.
  1624.    ENTRY is the file's entry.  */
  1625.  
  1626. void
  1627. read_header (desc, entry)
  1628.      int desc;
  1629.      register struct file_entry *entry;
  1630. {
  1631.   register int len;
  1632.   struct exec *loc = (struct exec *) &entry->header;
  1633.  
  1634.   lseek (desc, entry->starting_offset, 0);
  1635. #ifdef COFF_ENCAPSULATE
  1636.   if (entry->just_syms_flag)
  1637.     lseek (desc, sizeof(coffheader), 1);
  1638. #endif
  1639.   len = read (desc, loc, sizeof (struct exec));
  1640.   if (len != sizeof (struct exec))
  1641.     fatal_with_file ("failure reading header of ", entry);
  1642.   if (N_BADMAG (*loc))
  1643.     fatal_with_file ("bad magic number in ", entry);
  1644.  
  1645.   entry->header_read_flag = 1;
  1646. }
  1647.  
  1648. /* Read the symbols of file ENTRY into core.
  1649.    Assume it is already open, on descriptor DESC.
  1650.    Also read the length of the string table, which follows the symbol table,
  1651.    but don't read the contents of the string table.  */
  1652.  
  1653. void
  1654. read_entry_symbols (desc, entry)
  1655.      struct file_entry *entry;
  1656.      int desc;
  1657. {
  1658.   int str_size;
  1659.  
  1660.   if (!entry->header_read_flag)
  1661.     read_header (desc, entry);
  1662.  
  1663.   entry->symbols = (struct nlist *) xmalloc (entry->header.a_syms);
  1664.  
  1665.   lseek (desc, N_SYMOFF (entry->header) + entry->starting_offset, 0);
  1666.   if (entry->header.a_syms != read (desc, entry->symbols, entry->header.a_syms))
  1667.     fatal_with_file ("premature end of file in symbols of ", entry);
  1668.  
  1669.   lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  1670.   if (sizeof str_size != read (desc, &str_size, sizeof str_size))
  1671.     fatal_with_file ("bad string table size in ", entry);
  1672.  
  1673.   entry->string_size = str_size;
  1674. }
  1675.  
  1676. /* Read the string table of file ENTRY into core.
  1677.    Assume it is already open, on descriptor DESC.
  1678.    Also record whether a GDB symbol segment follows the string table.  */
  1679.  
  1680. void
  1681. read_entry_strings (desc, entry)
  1682.      struct file_entry *entry;
  1683.      int desc;
  1684. {
  1685.   int buffer;
  1686.  
  1687.   if (!entry->header_read_flag)
  1688.     read_header (desc, entry);
  1689.  
  1690.   lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  1691.   if (entry->string_size != read (desc, entry->strings, entry->string_size))
  1692.     fatal_with_file ("premature end of file in strings of ", entry);
  1693.  
  1694.   /* While we are here, see if the file has a symbol segment at the end.
  1695.      For a separate file, just try reading some more.
  1696.      For a library member, compare current pos against total size.  */
  1697.   if (entry->superfile)
  1698.     {
  1699.       if (entry->total_size == N_STROFF (entry->header) + entry->string_size)
  1700.     return;
  1701.     }
  1702.   else
  1703.     {
  1704.       buffer = read (desc, &buffer, sizeof buffer);
  1705.       if (buffer == 0)
  1706.     return;
  1707.       if (buffer != sizeof buffer)
  1708.     fatal_with_file ("premature end of file in GDB symbol segment of ", entry);
  1709.     }
  1710.   /* Don't try to do anything with symsegs.  */
  1711.   return;
  1712. #if 0
  1713.   /* eliminate warning of `statement not reached'.  */
  1714.   entry->symseg_offset = N_STROFF (entry->header) + entry->string_size;
  1715. #endif
  1716. }
  1717.  
  1718. /* Read in the symbols of all input files.  */
  1719.  
  1720. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  1721. void enter_file_symbols (), enter_global_ref (), search_library ();
  1722.  
  1723. void
  1724. load_symbols ()
  1725. {
  1726.   register int i;
  1727.  
  1728.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  1729.  
  1730.   for (i = 0; i < number_of_files; i++)
  1731.     {
  1732.       register struct file_entry *entry = &file_table[i];
  1733.       read_file_symbols (entry);
  1734.     }
  1735.  
  1736.   if (trace_files) fprintf (stderr, "\n");
  1737. }
  1738.  
  1739. /* If ENTRY is a rel file, read its symbol and string sections into core.
  1740.    If it is a library, search it and load the appropriate members
  1741.    (which means calling this function recursively on those members).  */
  1742.  
  1743. void
  1744. read_file_symbols (entry)
  1745.      register struct file_entry *entry;
  1746. {
  1747.   register int desc;
  1748.   register int len;
  1749.   struct exec hdr;
  1750.  
  1751.   desc = file_open (entry);
  1752.  
  1753. #ifdef COFF_ENCAPSULATE
  1754.   if (entry->just_syms_flag)
  1755.     lseek (desc, sizeof(coffheader),0);
  1756. #endif
  1757.  
  1758.   len = read (desc, &hdr, sizeof hdr);
  1759.   if (len != sizeof hdr)
  1760.     fatal_with_file ("failure reading header of ", entry);
  1761.  
  1762.   if (!N_BADMAG (hdr))
  1763.     {
  1764.       read_entry_symbols (desc, entry);
  1765.       entry->strings = (char *) alloca (entry->string_size);
  1766.       read_entry_strings (desc, entry);
  1767.       enter_file_symbols (entry);
  1768.       entry->strings = 0;
  1769.     }
  1770.   else
  1771.     {
  1772.       char armag[SARMAG];
  1773.  
  1774.       lseek (desc, 0, 0);
  1775.       if (SARMAG != read (desc, armag, SARMAG) || strncmp (armag, ARMAG, SARMAG))
  1776.     fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1777.       entry->library_flag = 1;
  1778.       search_library (desc, entry);
  1779.     }
  1780.  
  1781.   file_close ();
  1782. }
  1783.  
  1784. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  1785.  
  1786. void
  1787. enter_file_symbols (entry)
  1788.      struct file_entry *entry;
  1789. {
  1790.   register struct nlist
  1791.     *p,
  1792.     *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1793.  
  1794.   if (trace_files) prline_file_name (entry, stderr);
  1795.  
  1796.   for (p = entry->symbols; p < end; p++)
  1797.     {
  1798.       if (p->n_type == (N_SETV | N_EXT)) continue;
  1799.       if (set_element_prefixes
  1800.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  1801.     p->n_type += (N_SETA - N_ABS);
  1802.  
  1803.       if (SET_ELEMENT_P (p->n_type))
  1804.     {
  1805.       set_symbol_count++;
  1806.       if (!relocatable_output)
  1807.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1808.     }
  1809.       else if (p->n_type == N_WARNING)
  1810.     {
  1811.       char *name = p->n_un.n_strx + entry->strings;
  1812.  
  1813.       /* Grab the next entry.  */
  1814.       p++;
  1815.       if (p->n_type != (N_UNDF | N_EXT))
  1816.         {
  1817.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  1818.                progname, entry->filename);
  1819.           make_executable = 0;
  1820.           p--;        /* Process normally.  */
  1821.         }
  1822.       else
  1823.         {
  1824.           glosym *sp;
  1825.           char *sname = p->n_un.n_strx + entry->strings;
  1826.           /* Deal with the warning symbol.  */
  1827.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1828.           sp = getsym (sname);
  1829.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  1830.           strcpy (sp->warning, name);
  1831.           warning_count++;
  1832.         }
  1833.     }
  1834.       else if (p->n_type & N_EXT)
  1835.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1836.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  1837.     {
  1838.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  1839.         non_L_local_sym_count++;
  1840.       local_sym_count++;
  1841.     }
  1842.       else debugger_sym_count++;
  1843.     }
  1844.  
  1845.    /* Count one for the local symbol that we generate,
  1846.       whose name is the file's name (usually) and whose address
  1847.       is the start of the file's text.  */
  1848.  
  1849.   local_sym_count++;
  1850.   non_L_local_sym_count++;
  1851. }
  1852.  
  1853. /* Enter one global symbol in the hash table.
  1854.    NLIST_P points to the `struct nlist' read from the file
  1855.    that describes the global symbol.  NAME is the symbol's name.
  1856.    ENTRY is the file entry for the file the symbol comes from.
  1857.  
  1858.    The `struct nlist' is modified by placing it on a chain of
  1859.    all such structs that refer to the same global symbol.
  1860.    This chain starts in the `refs' field of the symbol table entry
  1861.    and is chained through the `n_name'.  */
  1862.  
  1863. void
  1864. enter_global_ref (nlist_p, name, entry)
  1865.      register struct nlist *nlist_p;
  1866.      char *name;
  1867.      struct file_entry *entry;
  1868. {
  1869.   register glosym *sp = getsym (name);
  1870.   register int type = nlist_p->n_type;
  1871.   int oldref = sp->referenced;
  1872.   int olddef = sp->defined;
  1873.  
  1874.   nlist_p->n_un.n_name = (char *) sp->refs;
  1875.   sp->refs = nlist_p;
  1876.  
  1877.   sp->referenced = 1;
  1878.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  1879.     {
  1880.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  1881.     sp->defined = type;
  1882.  
  1883.       if (oldref && !olddef)
  1884.     /* It used to be undefined and we're defining it.  */
  1885.     undefined_global_sym_count--;
  1886.  
  1887.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  1888.     {
  1889.       /* First definition and it's common.  */
  1890.       common_defined_global_count++;
  1891.       sp->max_common_size = nlist_p->n_value;
  1892.     }
  1893.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  1894.     {
  1895.       /* It used to be common and we're defining it as
  1896.          something else.  */
  1897.       common_defined_global_count--;
  1898.       sp->max_common_size = 0;
  1899.     }
  1900.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  1901.       && sp->max_common_size < nlist_p->n_value)
  1902.     /* It used to be common and this is a new common entry to
  1903.        which we need to pay attention.  */
  1904.     sp->max_common_size = nlist_p->n_value;
  1905.  
  1906.       /* Are we defining it as a set element?  */
  1907.       if (SET_ELEMENT_P (type)
  1908.       && (!olddef || (olddef && sp->max_common_size)))
  1909.     set_vector_count++;
  1910.       /* As an indirection?  */
  1911.       else if (type == (N_INDR | N_EXT))
  1912.     {
  1913.       /* Indirect symbols value should be modified to point
  1914.          a symbol being equivalenced to. */
  1915.       nlist_p->n_value
  1916.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  1917.                      + entry->strings);
  1918.       if ((glosym *) nlist_p->n_value == sp)
  1919.         {
  1920.           /* Somebody redefined a symbol to be itself.  */
  1921.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  1922.                entry->filename, name);
  1923.           /* Rewrite this symbol as being a global text symbol
  1924.          with value 0.  */
  1925.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  1926.           nlist_p->n_value = 0;
  1927.           /* Don't make the output executable.  */
  1928.           make_executable = 0;
  1929.         }
  1930.       else
  1931.         global_indirect_count++;
  1932.     }
  1933.     }
  1934.   else
  1935.     if (!oldref)
  1936. #ifndef DOLLAR_KLUDGE
  1937.       undefined_global_sym_count++;
  1938. #else
  1939.       {
  1940.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  1941.       {
  1942.         /* This is an (ISI?) $-conditional; skip it */
  1943.         sp->referenced = 0;
  1944.         if (sp->trace)
  1945.           {
  1946.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  1947.         print_file_name (entry, stderr);
  1948.         fprintf (stderr, "\n");
  1949.           }
  1950.         return;
  1951.       }
  1952.     else
  1953.       undefined_global_sym_count++;
  1954.       }
  1955. #endif
  1956.  
  1957.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  1958.     text_start = nlist_p->n_value;
  1959.  
  1960.   if (sp->trace)
  1961.     {
  1962.       register char *reftype;
  1963.       switch (type & N_TYPE)
  1964.     {
  1965.     case N_UNDF:
  1966.       if (nlist_p->n_value)
  1967.         reftype = "defined as common";
  1968.       else reftype = "referenced";
  1969.       break;
  1970.  
  1971.     case N_ABS:
  1972.       reftype = "defined as absolute";
  1973.       break;
  1974.  
  1975.     case N_TEXT:
  1976.       reftype = "defined in text section";
  1977.       break;
  1978.  
  1979.     case N_DATA:
  1980.       reftype = "defined in data section";
  1981.       break;
  1982.  
  1983.     case N_BSS:
  1984.       reftype = "defined in BSS section";
  1985.       break;
  1986.  
  1987.     case N_SETT:
  1988.       reftype = "is a text set element";
  1989.       break;
  1990.  
  1991.     case N_SETD:
  1992.       reftype = "is a data set element";
  1993.       break;
  1994.  
  1995.     case N_SETB:
  1996.       reftype = "is a BSS set element";
  1997.       break;
  1998.  
  1999.     case N_SETA:
  2000.       reftype = "is an absolute set element";
  2001.       break;
  2002.  
  2003.     case N_SETV:
  2004.       reftype = "defined in data section as vector";
  2005.       break;
  2006.  
  2007.     case N_INDR:
  2008.       reftype = (char *) alloca (23
  2009.                      + strlen ((nlist_p + 1)->n_un.n_strx
  2010.                            + entry->strings));
  2011.       sprintf (reftype, "defined equivalent to %s",
  2012.            (nlist_p + 1)->n_un.n_strx + entry->strings);
  2013.       break;
  2014.  
  2015. #ifdef sequent
  2016.     case N_SHUNDF:
  2017.       reftype = "shared undf";
  2018.       break;
  2019.  
  2020. /* These conflict with cases above.
  2021.     case N_SHDATA:
  2022.       reftype = "shared data";
  2023.       break;
  2024.  
  2025.     case N_SHBSS:
  2026.       reftype = "shared BSS";
  2027.       break;
  2028. */
  2029.     default:
  2030.       reftype = "I don't know this type";
  2031.       break;
  2032. #endif
  2033.     }
  2034.  
  2035.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2036.       print_file_name (entry, stderr);
  2037.       fprintf (stderr, "\n");
  2038.     }
  2039. }
  2040.  
  2041. /* This return 0 if the given file entry's symbol table does *not*
  2042.    contain the nlist point entry, and it returns the files entry
  2043.    pointer (cast to unsigned long) if it does. */
  2044.  
  2045. unsigned long
  2046. contains_symbol (entry, n_ptr)
  2047.      struct file_entry *entry;
  2048.      register struct nlist *n_ptr;
  2049. {
  2050.   if (n_ptr >= entry->symbols &&
  2051.       n_ptr < (entry->symbols
  2052.            + (entry->header.a_syms / sizeof (struct nlist))))
  2053.     return (unsigned long) entry;
  2054.   return 0;
  2055. }
  2056.  
  2057.  
  2058. /* Searching libraries */
  2059.  
  2060. struct file_entry *decode_library_subfile ();
  2061. void linear_library (), symdef_library ();
  2062.  
  2063. /* Search the library ENTRY, already open on descriptor DESC.
  2064.    This means deciding which library members to load,
  2065.    making a chain of `struct file_entry' for those members,
  2066.    and entering their global symbols in the hash table.  */
  2067.  
  2068. void
  2069. search_library (desc, entry)
  2070.      int desc;
  2071.      struct file_entry *entry;
  2072. {
  2073.   int member_length;
  2074.   register char *name;
  2075.   register struct file_entry *subentry;
  2076.  
  2077.   if (!undefined_global_sym_count) return;
  2078.  
  2079.   /* Examine its first member, which starts SARMAG bytes in.  */
  2080.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2081.   if (!subentry) return;
  2082.  
  2083.   name = subentry->filename;
  2084.   free (subentry);
  2085.  
  2086.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2087.  
  2088.   if (!strcmp (name, "__.SYMDEF"))
  2089.     symdef_library (desc, entry, member_length);
  2090.   else
  2091.     linear_library (desc, entry);
  2092. }
  2093.  
  2094. /* Construct and return a file_entry for a library member.
  2095.    The library's file_entry is library_entry, and the library is open on DESC.
  2096.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2097.    We store the length of the member into *LENGTH_LOC.  */
  2098.  
  2099. struct file_entry *
  2100. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2101.      int desc;
  2102.      struct file_entry *library_entry;
  2103.      int subfile_offset;
  2104.      int *length_loc;
  2105. {
  2106.   int bytes_read;
  2107.   register int namelen;
  2108.   int member_length;
  2109.   register char *name;
  2110.   struct ar_hdr hdr1;
  2111.   register struct file_entry *subentry;
  2112.  
  2113.   lseek (desc, subfile_offset, 0);
  2114.  
  2115.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2116.   if (!bytes_read)
  2117.     return 0;        /* end of archive */
  2118.  
  2119.   if (sizeof hdr1 != bytes_read)
  2120.     fatal_with_file ("malformed library archive ", library_entry);
  2121.  
  2122.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2123.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2124.  
  2125.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2126.   bzero (subentry, sizeof (struct file_entry));
  2127.  
  2128.   for (namelen = 0;
  2129.        namelen < sizeof hdr1.ar_name
  2130.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2131.        && hdr1.ar_name[namelen] != '/';
  2132.        namelen++);
  2133.  
  2134.   name = (char *) xmalloc (namelen+1);
  2135.   strncpy (name, hdr1.ar_name, namelen);
  2136.   name[namelen] = 0;
  2137.  
  2138.   subentry->filename = name;
  2139.   subentry->local_sym_name = name;
  2140.   subentry->symbols = 0;
  2141.   subentry->strings = 0;
  2142.   subentry->subfiles = 0;
  2143.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2144.   subentry->superfile = library_entry;
  2145.   subentry->library_flag = 0;
  2146.   subentry->header_read_flag = 0;
  2147.   subentry->just_syms_flag = 0;
  2148.   subentry->chain = 0;
  2149.   subentry->total_size = member_length;
  2150.  
  2151.   (*length_loc) = member_length;
  2152.  
  2153.   return subentry;
  2154. }
  2155.  
  2156. int subfile_wanted_p ();
  2157.  
  2158. /* Search a library that has a __.SYMDEF member.
  2159.    DESC is a descriptor on which the library is open.
  2160.      The file pointer is assumed to point at the __.SYMDEF data.
  2161.    ENTRY is the library's file_entry.
  2162.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2163.  
  2164. void
  2165. symdef_library (desc, entry, member_length)
  2166.      int desc;
  2167.      struct file_entry *entry;
  2168.      int member_length;
  2169. {
  2170.   int *symdef_data = (int *) xmalloc (member_length);
  2171.   register struct symdef *symdef_base;
  2172.   char *sym_name_base;
  2173.   int number_of_symdefs;
  2174.   int length_of_strings;
  2175.   int not_finished;
  2176.   int bytes_read;
  2177.   register int i;
  2178.   struct file_entry *prev = 0;
  2179.   int prev_offset = 0;
  2180.  
  2181.   bytes_read = read (desc, symdef_data, member_length);
  2182.   if (bytes_read != member_length)
  2183.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2184.  
  2185.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2186.   if (number_of_symdefs < 0 ||
  2187.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2188.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2189.  
  2190.   symdef_base = (struct symdef *) (symdef_data + 1);
  2191.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2192.  
  2193.   if (length_of_strings < 0
  2194.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2195.       + 2 * sizeof (int) != member_length)
  2196.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2197.  
  2198.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2199.  
  2200.   /* Check all the string indexes for validity.  */
  2201.  
  2202.   for (i = 0; i < number_of_symdefs; i++)
  2203.     {
  2204.       register int index = symdef_base[i].symbol_name_string_index;
  2205.       if (index < 0 || index >= length_of_strings
  2206.       || (index && *(sym_name_base + index - 1)))
  2207.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2208.     }
  2209.  
  2210.   /* Search the symdef data for members to load.
  2211.      Do this until one whole pass finds nothing to load.  */
  2212.  
  2213.   not_finished = 1;
  2214.   while (not_finished)
  2215.     {
  2216.       not_finished = 0;
  2217.  
  2218.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2219.      Load the library members that contain such symbols.  */
  2220.  
  2221.       for (i = 0;
  2222.        (i < number_of_symdefs
  2223.         && (undefined_global_sym_count || common_defined_global_count));
  2224.        i++)
  2225.     if (symdef_base[i].symbol_name_string_index >= 0)
  2226.       {
  2227.         register glosym *sp;
  2228.  
  2229.         sp = getsym_soft (sym_name_base
  2230.                   + symdef_base[i].symbol_name_string_index);
  2231.  
  2232.         /* If we find a symbol that appears to be needed, think carefully
  2233.            about the archive member that the symbol is in.  */
  2234.  
  2235.         if (sp && ((sp->referenced && !sp->defined)
  2236.                || (sp->defined && sp->max_common_size)))
  2237.           {
  2238.         int junk;
  2239.         register int j;
  2240.         register int offset = symdef_base[i].library_member_offset;
  2241.         struct file_entry *subentry;
  2242.  
  2243.         /* Don't think carefully about any archive member
  2244.            more than once in a given pass.  */
  2245.  
  2246.         if (prev_offset == offset)
  2247.           continue;
  2248.         prev_offset = offset;
  2249.  
  2250.         /* Read the symbol table of the archive member.  */
  2251.  
  2252.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2253.         if (subentry == 0)
  2254.           fatal ("invalid offset for %s in symbol table of %s",
  2255.              sym_name_base
  2256.              + symdef_base[i].symbol_name_string_index,
  2257.              entry->filename);
  2258.         read_entry_symbols (desc, subentry);
  2259.         subentry->strings = (char *) malloc (subentry->string_size);
  2260.         read_entry_strings (desc, subentry);
  2261.  
  2262.         /* Now scan the symbol table and decide whether to load.  */
  2263.  
  2264.         if (!subfile_wanted_p (subentry))
  2265.           {
  2266.             free (subentry->symbols);
  2267.             free (subentry);
  2268.           }
  2269.         else
  2270.           {
  2271.             /* This member is needed; load it.
  2272.                Since we are loading something on this pass,
  2273.                we must make another pass through the symdef data.  */
  2274.  
  2275.             not_finished = 1;
  2276.  
  2277.             enter_file_symbols (subentry);
  2278.  
  2279.             if (prev)
  2280.               prev->chain = subentry;
  2281.             else entry->subfiles = subentry;
  2282.             prev = subentry;
  2283.  
  2284.             /* Clear out this member's symbols from the symdef data
  2285.                so that following passes won't waste time on them.  */
  2286.  
  2287.             for (j = 0; j < number_of_symdefs; j++)
  2288.               {
  2289.             if (symdef_base[j].library_member_offset == offset)
  2290.               symdef_base[j].symbol_name_string_index = -1;
  2291.               }
  2292.           }
  2293.  
  2294.         /* We'll read the strings again if we need them again.  */
  2295.         free (subentry->strings);
  2296.         subentry->strings = 0;
  2297.           }
  2298.       }
  2299.     }
  2300.  
  2301.   free (symdef_data);
  2302. }
  2303.  
  2304. /* Search a library that has no __.SYMDEF.
  2305.    ENTRY is the library's file_entry.
  2306.    DESC is the descriptor it is open on.  */
  2307.  
  2308. void
  2309. linear_library (desc, entry)
  2310.      int desc;
  2311.      struct file_entry *entry;
  2312. {
  2313.   register struct file_entry *prev = 0;
  2314.   register int this_subfile_offset = SARMAG;
  2315.  
  2316.   while (undefined_global_sym_count || common_defined_global_count)
  2317.     {
  2318.       int member_length;
  2319.       register struct file_entry *subentry;
  2320.  
  2321.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2322.                      &member_length);
  2323.  
  2324.       if (!subentry) return;
  2325.  
  2326.       read_entry_symbols (desc, subentry);
  2327.       subentry->strings = (char *) alloca (subentry->string_size);
  2328.       read_entry_strings (desc, subentry);
  2329.  
  2330.       if (!subfile_wanted_p (subentry))
  2331.     {
  2332.       free (subentry->symbols);
  2333.       free (subentry);
  2334.     }
  2335.       else
  2336.     {
  2337.       enter_file_symbols (subentry);
  2338.  
  2339.       if (prev)
  2340.         prev->chain = subentry;
  2341.       else entry->subfiles = subentry;
  2342.       prev = subentry;
  2343.       subentry->strings = 0; /* Since space will dissapear on return */
  2344.     }
  2345.  
  2346.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2347.       if (this_subfile_offset & 1) this_subfile_offset++;
  2348.     }
  2349. }
  2350.  
  2351. /* ENTRY is an entry for a library member.
  2352.    Its symbols have been read into core, but not entered.
  2353.    Return nonzero if we ought to load this member.  */
  2354.  
  2355. int
  2356. subfile_wanted_p (entry)
  2357.      struct file_entry *entry;
  2358. {
  2359.   register struct nlist *p;
  2360.   register struct nlist *end
  2361.     = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2362. #ifdef DOLLAR_KLUDGE
  2363.   register int dollar_cond = 0;
  2364. #endif
  2365.  
  2366.   for (p = entry->symbols; p < end; p++)
  2367.     {
  2368.       register int type = p->n_type;
  2369.       register char *name = p->n_un.n_strx + entry->strings;
  2370.  
  2371.       /* If the symbol has an interesting definition, we could
  2372.      potentially want it.  */
  2373.       if (type & N_EXT
  2374.       && (type != (N_UNDF | N_EXT) || p->n_value
  2375.  
  2376. #ifdef DOLLAR_KLUDGE
  2377.            || name[1] == '$'
  2378. #endif
  2379.           )
  2380.       && !SET_ELEMENT_P (type)
  2381.       && !set_element_prefixed_p (name))
  2382.     {
  2383.       register glosym *sp = getsym_soft (name);
  2384.  
  2385. #ifdef DOLLAR_KLUDGE
  2386.       if (name[1] == '$')
  2387.         {
  2388.           sp = getsym_soft (&name[2]);
  2389.           dollar_cond = 1;
  2390.           if (!sp) continue;
  2391.           if (sp->referenced)
  2392.         {
  2393.           if (write_map)
  2394.             {
  2395.               print_file_name (entry, stdout);
  2396.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2397.             }
  2398.           return 1;
  2399.         }
  2400.           continue;
  2401.         }
  2402. #endif
  2403.  
  2404.       /* If this symbol has not been hashed, we can't be looking for it. */
  2405.  
  2406.       if (!sp) continue;
  2407.  
  2408.       if ((sp->referenced && !sp->defined)
  2409.           || (sp->defined && sp->max_common_size))
  2410.         {
  2411.           /* This is a symbol we are looking for.  It is either
  2412.              not yet defined or defined as a common.  */
  2413. #ifdef DOLLAR_KLUDGE
  2414.           if (dollar_cond) continue;
  2415. #endif
  2416.           if (type == (N_UNDF | N_EXT))
  2417.         {
  2418.           /* Symbol being defined as common.
  2419.              Remember this, but don't load subfile just for this.  */
  2420.  
  2421.           /* If it didn't used to be common, up the count of
  2422.              common symbols.  */
  2423.           if (!sp->max_common_size)
  2424.             common_defined_global_count++;
  2425.  
  2426.           if (sp->max_common_size < p->n_value)
  2427.             sp->max_common_size = p->n_value;
  2428.           if (!sp->defined)
  2429.             undefined_global_sym_count--;
  2430.           sp->defined = 1;
  2431.           continue;
  2432.         }
  2433.  
  2434.           if (write_map)
  2435.         {
  2436.           print_file_name (entry, stdout);
  2437.           fprintf (stdout, " needed due to %s\n", sp->name);
  2438.         }
  2439.           return 1;
  2440.         }
  2441.     }
  2442.     }
  2443.  
  2444.   return 0;
  2445. }
  2446.  
  2447. void consider_file_section_lengths (), relocate_file_addresses ();
  2448.  
  2449. /* Having entered all the global symbols and found the sizes of sections
  2450.    of all files to be linked, make all appropriate deductions from this data.
  2451.  
  2452.    We propagate global symbol values from definitions to references.
  2453.    We compute the layout of the output file and where each input file's
  2454.    contents fit into it.  */
  2455.  
  2456. void
  2457. digest_symbols ()
  2458. {
  2459.   register int i;
  2460.   int setv_fill_count;
  2461.  
  2462.   if (trace_files)
  2463.     fprintf (stderr, "Digesting symbol information:\n\n");
  2464.  
  2465.   /* Compute total size of sections */
  2466.  
  2467.   each_file (consider_file_section_lengths, 0);
  2468.  
  2469.   /* If necessary, pad text section to full page in the file.
  2470.      Include the padding in the text segment size.  */
  2471.  
  2472. #ifdef NMAGIC
  2473.   if (magic == ZMAGIC || magic == NMAGIC)
  2474. #else
  2475.   if (magic == ZMAGIC)
  2476. #endif
  2477.     {
  2478.       int text_end = text_size + N_TXTOFF (outheader);
  2479.       text_pad = ((text_end + page_size - 1) & (- page_size)) - text_end;
  2480.       text_size += text_pad;
  2481.     }
  2482.  
  2483. #ifdef _N_BASEADDR
  2484.   /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry.  */
  2485.   outheader.a_entry = N_PAGSIZ (outheader);
  2486. #endif
  2487.  
  2488.   outheader.a_text = text_size;
  2489. #ifdef sequent
  2490.   outheader.a_text += N_ADDRADJ (outheader);
  2491. #endif
  2492.  
  2493.   /* Make the data segment address start in memory on a suitable boundary.  */
  2494.  
  2495.   if (! Tdata_flag_specified)
  2496.     data_start = N_DATADDR (outheader) + text_start - TEXT_START (outheader);
  2497.  
  2498.   /* Set up the set element vector */
  2499.  
  2500.   if (!relocatable_output)
  2501.     {
  2502.       /* The set sector size is the number of set elements + a word
  2503.          for each symbol for the length word at the beginning of the
  2504.      vector, plus a word for each symbol for a zero at the end of
  2505.      the vector (for incremental linking).  */
  2506.       set_sect_size
  2507.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  2508.       set_sect_start = data_start + data_size;
  2509.       data_size += set_sect_size;
  2510.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  2511.       setv_fill_count = 0;
  2512.     }
  2513.  
  2514.   /* Compute start addresses of each file's sections and symbols.  */
  2515.  
  2516.   each_full_file (relocate_file_addresses, 0);
  2517.  
  2518.   /* Now, for each symbol, verify that it is defined globally at most once.
  2519.      Put the global value into the symbol entry.
  2520.      Common symbols are allocated here, in the BSS section.
  2521.      Each defined symbol is given a '->defined' field
  2522.       which is the correct N_ code for its definition,
  2523.       except in the case of common symbols with -r.
  2524.      Then make all the references point at the symbol entry
  2525.      instead of being chained together. */
  2526.  
  2527.   defined_global_sym_count = 0;
  2528.  
  2529.   for (i = 0; i < TABSIZE; i++)
  2530.     {
  2531.       register glosym *sp;
  2532.       for (sp = symtab[i]; sp; sp = sp->link)
  2533.     {
  2534.       /* For each symbol */
  2535.       register struct nlist *p, *next;
  2536.       int defs = 0, com = sp->max_common_size;
  2537.       struct nlist *first_definition;
  2538.       for (p = sp->refs; p; p = next)
  2539.         {
  2540.           register int type = p->n_type;
  2541.  
  2542.           if (SET_ELEMENT_P (type))
  2543.         {
  2544.           if (relocatable_output)
  2545.             fatal ("internal: global ref to set element with -r");
  2546.           if (!defs++)
  2547.             {
  2548.               sp->value = set_sect_start
  2549.             + setv_fill_count++ * sizeof (unsigned long);
  2550.               sp->defined = N_SETV | N_EXT;
  2551.               first_definition = p;
  2552.             }
  2553.           else if ((sp->defined & ~N_EXT) != N_SETV)
  2554.             {
  2555.               sp->multiply_defined = 1;
  2556.               multiple_def_count++;
  2557.             }
  2558.           set_vectors[setv_fill_count++] = p->n_value;
  2559.         }
  2560.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  2561.         {
  2562.           /* non-common definition */
  2563.           if (defs++ && sp->value != p->n_value)
  2564.             {
  2565.               sp->multiply_defined = 1;
  2566.               multiple_def_count++;
  2567.             }
  2568.           sp->value = p->n_value;
  2569.           sp->defined = type;
  2570.           first_definition = p;
  2571.         }
  2572.           next = (struct nlist *) p->n_un.n_name;
  2573.           p->n_un.n_name = (char *) sp;
  2574.         }
  2575.       /* Allocate as common if defined as common and not defined for real */
  2576.       if (com && !defs)
  2577.         {
  2578.           if (!relocatable_output || force_common_definition)
  2579.         {
  2580.           int align = sizeof (int);
  2581.  
  2582.           /* Round up to nearest sizeof (int).  I don't know
  2583.              whether this is necessary or not (given that
  2584.              alignment is taken care of later), but it's
  2585.              traditional, so I'll leave it in.  Note that if
  2586.              this size alignment is ever removed, ALIGN above
  2587.              will have to be initialized to 1 instead of
  2588.              sizeof (int).  */
  2589.  
  2590.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  2591.  
  2592.           while (!(com & align))
  2593.             align <<= 1;
  2594.  
  2595.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  2596.  
  2597.           bss_size = ((((bss_size + data_size + data_start)
  2598.                   + (align - 1)) & (- align))
  2599.                   - data_size - data_start);
  2600.  
  2601.           sp->value = data_start + data_size + bss_size;
  2602.           sp->defined = N_BSS | N_EXT;
  2603.           bss_size += com;
  2604.           if (write_map)
  2605.             printf ("Allocating common %s: %x at %x\n",
  2606.                 sp->name, com, sp->value);
  2607.         }
  2608.           else
  2609.         {
  2610.           sp->defined = 0;
  2611.           undefined_global_sym_count++;
  2612.         }
  2613.         }
  2614.       /* Set length word at front of vector and zero byte at end.
  2615.          Reverse the vector itself to put it in file order.  */
  2616.       if ((sp->defined & ~N_EXT) == N_SETV)
  2617.         {
  2618.           unsigned long length_word_index
  2619.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  2620.           unsigned long i, tmp;
  2621.  
  2622.           set_vectors[length_word_index]
  2623.         = setv_fill_count - 1 - length_word_index;
  2624.  
  2625.           /* Reverse the vector.  */
  2626.           for (i = 1;
  2627.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  2628.            i++)
  2629.         {
  2630.           tmp = set_vectors[length_word_index + i];
  2631.           set_vectors[length_word_index + i]
  2632.             = set_vectors[setv_fill_count - i];
  2633.           set_vectors[setv_fill_count - i] = tmp;
  2634.         }
  2635.  
  2636.           set_vectors[setv_fill_count++] = 0;
  2637.         }
  2638.       if (sp->defined)
  2639.         defined_global_sym_count++;
  2640.     }
  2641.     }
  2642.  
  2643.   if (end_symbol)        /* These are null if -r.  */
  2644.     {
  2645.       etext_symbol->value = text_size + text_start;
  2646.       edata_symbol->value = data_start + data_size;
  2647.       end_symbol->value = data_start + data_size + bss_size;
  2648.     }
  2649.  
  2650.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  2651.  
  2652.   if (specified_data_size && specified_data_size > data_size)
  2653.     data_pad = specified_data_size - data_size;
  2654.  
  2655.   if (magic == ZMAGIC)
  2656.     data_pad = ((data_pad + data_size + page_size - 1) & (- page_size))
  2657.                - data_size;
  2658.  
  2659.   bss_size -= data_pad;
  2660.   if (bss_size < 0) bss_size = 0;
  2661.  
  2662.   data_size += data_pad;
  2663. }
  2664.  
  2665. /* Accumulate the section sizes of input file ENTRY
  2666.    into the section sizes of the output file.  */
  2667.  
  2668. void
  2669. consider_file_section_lengths (entry)
  2670.      register struct file_entry *entry;
  2671. {
  2672.   if (entry->just_syms_flag)
  2673.     return;
  2674.  
  2675.   entry->text_start_address = text_size;
  2676.   /* If there were any vectors, we need to chop them off */
  2677.   text_size += entry->header.a_text;
  2678.   entry->data_start_address = data_size;
  2679.   data_size += entry->header.a_data;
  2680.   entry->bss_start_address = bss_size;
  2681.   bss_size += entry->header.a_bss;
  2682.  
  2683.   text_reloc_size += entry->header.a_trsize;
  2684.   data_reloc_size += entry->header.a_drsize;
  2685. }
  2686.  
  2687. /* Determine where the sections of ENTRY go into the output file,
  2688.    whose total section sizes are already known.
  2689.    Also relocate the addresses of the file's local and debugger symbols.  */
  2690.  
  2691. void
  2692. relocate_file_addresses (entry)
  2693.      register struct file_entry *entry;
  2694. {
  2695.   entry->text_start_address += text_start;
  2696.   /* Note that `data_start' and `data_size' have not yet been
  2697.      adjusted for `data_pad'.  If they had been, we would get the wrong
  2698.      results here.  */
  2699.   entry->data_start_address += data_start;
  2700.   entry->bss_start_address += data_start + data_size;
  2701.  
  2702.   {
  2703.     register struct nlist *p;
  2704.     register struct nlist *end
  2705.       = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2706.  
  2707.     for (p = entry->symbols; p < end; p++)
  2708.       {
  2709.     /* If this belongs to a section, update it by the section's start address */
  2710.     register int type = p->n_type & N_TYPE;
  2711.  
  2712.     switch (type)
  2713.       {
  2714.       case N_TEXT:
  2715.       case N_SETT:
  2716.         p->n_value += entry->text_start_address;
  2717.         break;
  2718.       case N_DATA:
  2719.       case N_SETV:
  2720.       case N_SETD:
  2721.         /* A symbol whose value is in the data section
  2722.            is present in the input file as if the data section
  2723.            started at an address equal to the length of the file's text.  */
  2724.         p->n_value += entry->data_start_address - entry->header.a_text;
  2725.         break;
  2726.       case N_BSS:
  2727.       case N_SETB:
  2728.         /* likewise for symbols with value in BSS.  */
  2729.         p->n_value += entry->bss_start_address
  2730.           - entry->header.a_text - entry->header.a_data;
  2731.         break;
  2732.       }
  2733.       }
  2734.   }
  2735. }
  2736.  
  2737. void describe_file_sections (), list_file_locals ();
  2738.  
  2739. /* Print a complete or partial map of the output file.  */
  2740.  
  2741. void
  2742. print_symbols (outfile)
  2743.      FILE *outfile;
  2744. {
  2745.   register int i;
  2746.  
  2747.   fprintf (outfile, "\nFiles:\n\n");
  2748.  
  2749.   each_file (describe_file_sections, outfile);
  2750.  
  2751.   fprintf (outfile, "\nGlobal symbols:\n\n");
  2752.  
  2753.   for (i = 0; i < TABSIZE; i++)
  2754.     {
  2755.       register glosym *sp;
  2756.       for (sp = symtab[i]; sp; sp = sp->link)
  2757.     {
  2758.       if (sp->defined == 1)
  2759.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  2760.       if (sp->defined)
  2761.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  2762.       else if (sp->referenced)
  2763.         fprintf (outfile, "  %s: undefined\n", sp->name);
  2764.     }
  2765.     }
  2766.  
  2767.   each_file (list_file_locals, outfile);
  2768. }
  2769.  
  2770. void
  2771. describe_file_sections (entry, outfile)
  2772.      struct file_entry *entry;
  2773.      FILE *outfile;
  2774. {
  2775.   fprintf (outfile, "  ");
  2776.   print_file_name (entry, outfile);
  2777.   if (entry->just_syms_flag)
  2778.     fprintf (outfile, " symbols only\n", 0);
  2779.   else
  2780.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  2781.          entry->text_start_address, entry->header.a_text,
  2782.          entry->data_start_address, entry->header.a_data,
  2783.          entry->bss_start_address, entry->header.a_bss);
  2784. }
  2785.  
  2786. void
  2787. list_file_locals (entry, outfile)
  2788.      struct file_entry *entry;
  2789.      FILE *outfile;
  2790. {
  2791.   register struct nlist
  2792.     *p,
  2793.     *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2794.  
  2795.   entry->strings = (char *) alloca (entry->string_size);
  2796.   read_entry_strings (file_open (entry), entry);
  2797.  
  2798.   fprintf (outfile, "\nLocal symbols of ");
  2799.   print_file_name (entry, outfile);
  2800.   fprintf (outfile, ":\n\n");
  2801.  
  2802.   for (p = entry->symbols; p < end; p++)
  2803.     /* If this is a definition,
  2804.        update it if necessary by this file's start address.  */
  2805.     if (!(p->n_type & (N_STAB | N_EXT)))
  2806.       fprintf (outfile, "  %s: 0x%x\n",
  2807.            entry->strings + p->n_un.n_strx, p->n_value);
  2808.  
  2809.   entry->strings = 0;        /* All done with them.  */
  2810. }
  2811.  
  2812.  
  2813. /* Static vars for do_warnings and subroutines of it */
  2814. int list_unresolved_refs;    /* List unresolved refs */
  2815. int list_warning_symbols;    /* List warning syms */
  2816. int list_multiple_defs;        /* List multiple definitions */
  2817.  
  2818. /*
  2819.  * Structure for communication between do_file_warnings and it's
  2820.  * helper routines.  Will in practice be an array of three of these:
  2821.  * 0) Current line, 1) Next line, 2) Source file info.
  2822.  */
  2823. struct line_debug_entry
  2824. {
  2825.   int line;
  2826.   char *filename;
  2827.   struct nlist *sym;
  2828. };
  2829.  
  2830. void qsort ();
  2831. /*
  2832.  * Helper routines for do_file_warnings.
  2833.  */
  2834.  
  2835. /* Return an integer less than, equal to, or greater than 0 as per the
  2836.    relation between the two relocation entries.  Used by qsort.  */
  2837.  
  2838. int
  2839. relocation_entries_relation (rel1, rel2)
  2840.      struct relocation_info *rel1, *rel2;
  2841. {
  2842.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  2843. }
  2844.  
  2845. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  2846.    determines the type of the debugging symbol to look for (DSLINE or
  2847.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  2848.    the file.  It assumes that state_pointer[1] is valid; ie
  2849.    that it.sym points into some entry in the symbol table.  If
  2850.    state_pointer[1].sym == 0, this routine should not be called.  */
  2851.  
  2852. int
  2853. next_debug_entry (use_data_symbols, state_pointer)
  2854.      register int use_data_symbols;
  2855.      /* Next must be passed by reference! */
  2856.      struct line_debug_entry state_pointer[3];
  2857. {
  2858.   register struct line_debug_entry
  2859.     *current = state_pointer,
  2860.     *next = state_pointer + 1,
  2861.     /* Used to store source file */
  2862.     *source = state_pointer + 2;
  2863.   struct file_entry *entry = (struct file_entry *) source->sym;
  2864.  
  2865.   current->sym = next->sym;
  2866.   current->line = next->line;
  2867.   current->filename = next->filename;
  2868.  
  2869.   while (++(next->sym) < (entry->symbols
  2870.               + entry->header.a_syms/sizeof (struct nlist)))
  2871.     {
  2872.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  2873.        * may look negative...therefore, must mask to low bits
  2874.        */
  2875.       switch (next->sym->n_type & 0xff)
  2876.     {
  2877.     case N_SLINE:
  2878.       if (use_data_symbols) continue;
  2879.       next->line = next->sym->n_desc;
  2880.       return 1;
  2881.     case N_DSLINE:
  2882.       if (!use_data_symbols) continue;
  2883.       next->line = next->sym->n_desc;
  2884.       return 1;
  2885. #ifdef HAVE_SUN_STABS
  2886.     case N_EINCL:
  2887.       next->filename = source->filename;
  2888.       continue;
  2889. #endif
  2890.     case N_SO:
  2891.       source->filename = next->sym->n_un.n_strx + entry->strings;
  2892.       source->line++;
  2893. #ifdef HAVE_SUN_STABS
  2894.     case N_BINCL:
  2895. #endif
  2896.     case N_SOL:
  2897.       next->filename
  2898.         = next->sym->n_un.n_strx + entry->strings;
  2899.     default:
  2900.       continue;
  2901.     }
  2902.     }
  2903.   next->sym = (struct nlist *) 0;
  2904.   return 0;
  2905. }
  2906.  
  2907. /* Create a structure to save the state of a scan through the debug
  2908.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  2909.    DSLINE's instead of SLINE's.  entry is the file entry which points
  2910.    at the symbols to use.  */
  2911.  
  2912. struct line_debug_entry *
  2913. init_debug_scan (use_data_symbols, entry)
  2914.      int use_data_symbols;
  2915.      struct file_entry *entry;
  2916. {
  2917.   struct line_debug_entry
  2918.     *state_pointer
  2919.       = (struct line_debug_entry *)
  2920.     xmalloc (3 * sizeof (struct line_debug_entry));
  2921.   register struct line_debug_entry
  2922.     *current = state_pointer,
  2923.     *next = state_pointer + 1,
  2924.     *source = state_pointer + 2; /* Used to store source file */
  2925.  
  2926.   struct nlist *tmp;
  2927.  
  2928.   for (tmp = entry->symbols;
  2929.        tmp < (entry->symbols
  2930.           + entry->header.a_syms/sizeof (struct nlist));
  2931.        tmp++)
  2932.     if (tmp->n_type == (int) N_SO)
  2933.       break;
  2934.  
  2935.   if (tmp >= (entry->symbols
  2936.           + entry->header.a_syms/sizeof (struct nlist)))
  2937.     {
  2938.       /* I believe this translates to "We lose" */
  2939.       current->filename = next->filename = entry->filename;
  2940.       current->line = next->line = -1;
  2941.       current->sym = next->sym = (struct nlist *) 0;
  2942.       return state_pointer;
  2943.     }
  2944.  
  2945.   next->line = source->line = 0;
  2946.   next->filename = source->filename
  2947.     = (tmp->n_un.n_strx + entry->strings);
  2948.   source->sym = (struct nlist *) entry;
  2949.   next->sym = tmp;
  2950.  
  2951.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  2952.  
  2953.   if (!next->sym)        /* No line numbers for this section; */
  2954.                 /* setup output results as appropriate */
  2955.     {
  2956.       if (source->line)
  2957.     {
  2958.       current->filename = source->filename = entry->filename;
  2959.       current->line = -1;    /* Don't print lineno */
  2960.     }
  2961.       else
  2962.     {
  2963.       current->filename = source->filename;
  2964.       current->line = 0;
  2965.     }
  2966.       return state_pointer;
  2967.     }
  2968.  
  2969.  
  2970.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  2971.  
  2972.   return state_pointer;
  2973. }
  2974.  
  2975. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  2976.    which describes the current location in the implied scan through
  2977.    the debug symbols within the file which ADDRESS is within, and
  2978.    returns the source line number which corresponds to ADDRESS.  */
  2979.  
  2980. int
  2981. address_to_line (address, state_pointer)
  2982.      unsigned long address;
  2983.      /* Next must be passed by reference! */
  2984.      struct line_debug_entry state_pointer[3];
  2985. {
  2986.   struct line_debug_entry
  2987.     *current = state_pointer,
  2988.     *next = state_pointer + 1;
  2989.   struct line_debug_entry *tmp_pointer;
  2990.  
  2991.   int use_data_symbols;
  2992.  
  2993.   if (next->sym)
  2994.     use_data_symbols = (next->sym->n_type & N_TYPE) == N_DATA;
  2995.   else
  2996.     return current->line;
  2997.  
  2998.   /* Go back to the beginning if we've already passed it.  */
  2999.   if (current->sym->n_value > address)
  3000.     {
  3001.       tmp_pointer = init_debug_scan (use_data_symbols,
  3002.                      (struct file_entry *)
  3003.                      ((state_pointer + 2)->sym));
  3004.       state_pointer[0] = tmp_pointer[0];
  3005.       state_pointer[1] = tmp_pointer[1];
  3006.       state_pointer[2] = tmp_pointer[2];
  3007.       free (tmp_pointer);
  3008.     }
  3009.  
  3010.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3011.   if (current->sym->n_value > address)
  3012.     return -1;
  3013.  
  3014.   while (next->sym
  3015.      && next->sym->n_value <= address
  3016.      && next_debug_entry (use_data_symbols, state_pointer))
  3017.     ;
  3018.   return current->line;
  3019. }
  3020.  
  3021.  
  3022. /* Macros for manipulating bitvectors.  */
  3023. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3024. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3025.  
  3026. /* This routine will scan through the relocation data of file ENTRY,
  3027.    printing out references to undefined symbols and references to
  3028.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3029.    is non-zero, it will scan the data relocation segment (and use
  3030.    N_DSLINE symbols to track line number); otherwise it will scan the
  3031.    text relocation segment.  Warnings will be printed on the output
  3032.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3033.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3034.    we scan the nlists themselves.  */
  3035.  
  3036. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3037.      struct file_entry *entry;
  3038.      int data_segment;
  3039.      FILE *outfile;
  3040.      unsigned char *nlist_bitvector;
  3041. {
  3042.   struct relocation_info
  3043.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3044.     *reloc;
  3045.   int reloc_size
  3046.     = ((data_segment ? entry->header.a_drsize : entry->header.a_trsize)
  3047.        / sizeof (struct relocation_info));
  3048.   int start_of_segment
  3049.     = (data_segment ? entry->data_start_address : entry->text_start_address);
  3050.   struct nlist *start_of_syms = entry->symbols;
  3051.   struct line_debug_entry *state_pointer
  3052.     = init_debug_scan (data_segment != 0, entry);
  3053.   register struct line_debug_entry
  3054.     *current = state_pointer;
  3055.   /* Assigned to generally static values; should not be written into.  */
  3056.   char *errfmt;
  3057.   /* Assigned to alloca'd values cand copied into; should be freed
  3058.      when done.  */
  3059.   char *errmsg;
  3060.   int invalidate_line_number;
  3061.  
  3062.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3063.      for one lousy error optimization. */
  3064.  
  3065.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3066.      relocation_entries_relation);
  3067.  
  3068.   for (reloc = reloc_start;
  3069.        reloc < (reloc_start + reloc_size);
  3070.        reloc++)
  3071.     {
  3072.       register struct nlist *s;
  3073.       register glosym *g;
  3074.  
  3075.       /* If the relocation isn't resolved through a symbol, continue */
  3076.       if (!RELOC_EXTERN_P(reloc))
  3077.     continue;
  3078.  
  3079.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3080.  
  3081.       /* Local symbols shouldn't ever be used by relocation info, so
  3082.      the next should be safe.
  3083.      This is, of course, wrong.  References to local BSS symbols can be
  3084.      the targets of relocation info, and they can (must) be
  3085.      resolved through symbols.  However, these must be defined properly,
  3086.      (the assembler would have caught it otherwise), so we can
  3087.      ignore these cases.  */
  3088.       if (!(s->n_type & N_EXT))
  3089.     continue;
  3090.  
  3091.       g = (glosym *) s->n_un.n_name;
  3092.       errmsg = 0;
  3093.  
  3094.       if (!g->defined && list_unresolved_refs) /* Reference */
  3095.     {
  3096.       /* Mark as being noted by relocation warning pass.  */
  3097.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3098.  
  3099.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3100.         continue;
  3101.  
  3102.       /* Undefined symbol which we should mention */
  3103.  
  3104.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3105.         {
  3106.           errfmt = "More undefined symbol %s refs follow";
  3107.           invalidate_line_number = 1;
  3108.         }
  3109.       else
  3110.         {
  3111.           errfmt = "Undefined symbol %s referenced from %s segment";
  3112.           invalidate_line_number = 0;
  3113.         }
  3114.     }
  3115.       else                         /* Defined */
  3116.     {
  3117.       /* Potential symbol warning here */
  3118.       if (!g->warning) continue;
  3119.  
  3120.       /* Mark as being noted by relocation warning pass.  */
  3121.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3122.  
  3123.       errfmt = 0;
  3124.       errmsg = g->warning;
  3125.       invalidate_line_number = 0;
  3126.     }
  3127.  
  3128.  
  3129.       /* If errfmt == 0, errmsg has already been defined.  */
  3130.       if (errfmt != 0)
  3131.     {
  3132.       char *nm;
  3133.  
  3134.       if (demangler == NULL || (nm = (*demangler)(g->name)) == NULL)
  3135.         nm = g->name;
  3136.       errmsg = (char *) xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3137.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3138.       if (nm != g->name)
  3139.         free (nm);
  3140.     }
  3141.  
  3142.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3143.                state_pointer);
  3144.  
  3145.       if (current->line >=0)
  3146.     fprintf (outfile, "%s:%d: %s\n", current->filename,
  3147.          invalidate_line_number ? 0 : current->line, errmsg);
  3148.       else
  3149.     fprintf (outfile, "%s: %s\n", current->filename, errmsg);
  3150.  
  3151.       if (errfmt != 0)
  3152.     free (errmsg);
  3153.     }
  3154.  
  3155.   free (state_pointer);
  3156. }
  3157.  
  3158. /* Print on OUTFILE a list of all warnings generated by references
  3159.    and/or definitions in the file ENTRY.  List source file and line
  3160.    number if possible, just the .o file if not. */
  3161.  
  3162. void
  3163. do_file_warnings (entry, outfile)
  3164.      struct file_entry *entry;
  3165.      FILE *outfile;
  3166. {
  3167.   int number_of_syms = entry->header.a_syms / sizeof (struct nlist);
  3168.   unsigned char *nlist_bitvector
  3169.     = (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3170.   struct line_debug_entry *text_scan, *data_scan;
  3171.   int i;
  3172.   char *errfmt, *file_name;
  3173.   int line_number;
  3174.   int dont_allow_symbol_name;
  3175.  
  3176.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3177.  
  3178.   /* Read in the files strings if they aren't available */
  3179.   if (!entry->strings)
  3180.     {
  3181.       int desc;
  3182.  
  3183.       entry->strings = (char *) alloca (entry->string_size);
  3184.       desc = file_open (entry);
  3185.       read_entry_strings (desc, entry);
  3186.     }
  3187.  
  3188.   read_file_relocation (entry);
  3189.  
  3190.   /* Do text warnings based on a scan through the relocation info.  */
  3191.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3192.  
  3193.   /* Do data warnings based on a scan through the relocation info.  */
  3194.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3195.  
  3196.   /* Scan through all of the nlist entries in this file and pick up
  3197.      anything that the scan through the relocation stuff didn't.  */
  3198.  
  3199.   text_scan = init_debug_scan (0, entry);
  3200.   data_scan = init_debug_scan (1, entry);
  3201.  
  3202.   for (i = 0; i < number_of_syms; i++)
  3203.     {
  3204.       struct nlist *s;
  3205.       struct glosym *g;
  3206.  
  3207.       s = entry->symbols + i;
  3208.  
  3209.       if (!(s->n_type & N_EXT))
  3210.     continue;
  3211.  
  3212.       g = (glosym *) s->n_un.n_name;
  3213.       dont_allow_symbol_name = 0;
  3214.  
  3215.       if (list_multiple_defs && g->multiply_defined)
  3216.     {
  3217.       errfmt = "Definition of symbol %s (multiply defined)";
  3218.       switch (s->n_type)
  3219.         {
  3220.         case N_TEXT | N_EXT:
  3221.           line_number = address_to_line (s->n_value, text_scan);
  3222.           file_name = text_scan[0].filename;
  3223.           break;
  3224.         case N_DATA | N_EXT:
  3225.           line_number = address_to_line (s->n_value, data_scan);
  3226.           file_name = data_scan[0].filename;
  3227.           break;
  3228.         case N_SETA | N_EXT:
  3229.         case N_SETT | N_EXT:
  3230.         case N_SETD | N_EXT:
  3231.         case N_SETB | N_EXT:
  3232.           if (g->multiply_defined == 2)
  3233.         continue;
  3234.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3235.           break;
  3236.         default:
  3237.           continue;        /* Don't print out multiple defs
  3238.                    at references.  */
  3239.         }
  3240.     }
  3241.       else if (BIT_SET_P (nlist_bitvector, i))
  3242.     continue;
  3243.       else if (list_unresolved_refs && !g->defined)
  3244.     {
  3245.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3246.         continue;
  3247.  
  3248.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3249.         errfmt = "More undefined \"%s\" refs follow";
  3250.       else
  3251.         errfmt = "Undefined symbol \"%s\" referenced";
  3252.       line_number = -1;
  3253.     }
  3254.       else if (g->warning)
  3255.     {
  3256.       /* There are two cases in which we don't want to
  3257.          do this.  The first is if this is a definition instead of
  3258.          a reference.  The second is if it's the reference used by
  3259.          the warning stabs itself.  */
  3260.       if (s->n_type != (N_EXT | N_UNDF)
  3261.           || (i && (s-1)->n_type == N_WARNING))
  3262.         continue;
  3263.  
  3264.       errfmt = g->warning;
  3265.       line_number = -1;
  3266.       dont_allow_symbol_name = 1;
  3267.     }
  3268.       else
  3269.     continue;
  3270.  
  3271.       if (line_number == -1)
  3272.     fprintf (outfile, "%s: ", entry->filename);
  3273.       else
  3274.     fprintf (outfile, "%s:%d: ", file_name, line_number);
  3275.  
  3276.       if (dont_allow_symbol_name)
  3277.     fprintf (outfile, "%s", errfmt);
  3278.       else
  3279.     {
  3280.       char *nm;
  3281.       if (demangler != NULL && (nm = (*demangler)(g->name)) != NULL)
  3282.         {
  3283.           fprintf (outfile, errfmt, nm);
  3284.           free (nm);
  3285.         }
  3286.       else
  3287.         fprintf (outfile, errfmt, g->name);
  3288.     }
  3289.  
  3290.       fputc ('\n', outfile);
  3291.     }
  3292.   free (text_scan);
  3293.   free (data_scan);
  3294.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3295. }
  3296.  
  3297. do_warnings (outfile)
  3298.      FILE *outfile;
  3299. {
  3300.   list_unresolved_refs = /* !relocatable_output && */ undefined_global_sym_count;
  3301.   list_warning_symbols = warning_count;
  3302.   list_multiple_defs = multiple_def_count != 0;
  3303.  
  3304.   if (!(list_unresolved_refs ||
  3305.     list_warning_symbols ||
  3306.     list_multiple_defs      ))
  3307.     /* No need to run this routine */
  3308.     return;
  3309.  
  3310.   each_file (do_file_warnings, outfile);
  3311.  
  3312.   if ((list_unresolved_refs && !relocatable_output) || list_multiple_defs) 
  3313.     make_executable = 0;
  3314.  
  3315. }
  3316.  
  3317. /* Write the output file */
  3318.  
  3319. void
  3320. write_output ()
  3321. {
  3322.   struct stat statbuf;
  3323.   int filemode;
  3324.  
  3325.   (void) unlink (output_filename);
  3326.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3327.   if (outdesc < 0) perror_name (output_filename);
  3328.  
  3329.   if (fstat (outdesc, &statbuf) < 0)
  3330.     perror_name (output_filename);
  3331.  
  3332.   filemode = statbuf.st_mode;
  3333. #ifndef THINK_C
  3334.   chmod (output_filename, filemode & ~0111);
  3335. #endif
  3336.   /* Output the a.out header.  */
  3337.   write_header ();
  3338.  
  3339.   /* Output the text and data segments, relocating as we go.  */
  3340.   write_text ();
  3341.   write_data ();
  3342.  
  3343.   /* Output the merged relocation info, if requested with `-r'.  */
  3344.   if (relocatable_output)
  3345.     write_rel ();
  3346.  
  3347.   /* Output the symbol table (both globals and locals).  */
  3348.   write_syms ();
  3349.  
  3350.   /* Copy any GDB symbol segments from input files.  */
  3351.   write_symsegs ();
  3352.   close (outdesc);
  3353.  
  3354. #ifdef THINK_C
  3355.   makeresourcefile();
  3356. #else
  3357.   if (chmod (output_filename, filemode | 0111) == -1)
  3358.     perror_name (output_filename);
  3359. #endif
  3360. }
  3361.  
  3362. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  3363.  
  3364. void
  3365. write_header ()
  3366. {
  3367.   N_SET_MAGIC (outheader, magic);
  3368.   outheader.a_text = text_size;
  3369. #ifdef sequent
  3370.   outheader.a_text += N_ADDRADJ (outheader);
  3371.   if (entry_symbol == 0)
  3372.     entry_symbol = getsym("start");
  3373. #endif
  3374.   outheader.a_data = data_size;
  3375.   outheader.a_bss = bss_size;
  3376.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  3377.                : text_start + entry_offset);
  3378. #ifdef COFF_ENCAPSULATE
  3379.   if (need_coff_header)
  3380.     {
  3381.       /* We are encapsulating BSD format within COFF format.  */
  3382.       struct coffscn *tp, *dp, *bp;
  3383.  
  3384.       tp = &coffheader.scns[0];
  3385.       dp = &coffheader.scns[1];
  3386.       bp = &coffheader.scns[2];
  3387.  
  3388.       strcpy (tp->s_name, ".text");
  3389.       tp->s_paddr = text_start;
  3390.       tp->s_vaddr = text_start;
  3391.       tp->s_size = text_size;
  3392.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  3393.       tp->s_relptr = 0;
  3394.       tp->s_lnnoptr = 0;
  3395.       tp->s_nreloc = 0;
  3396.       tp->s_nlnno = 0;
  3397.       tp->s_flags = 0x20;
  3398.       strcpy (dp->s_name, ".data");
  3399.       dp->s_paddr = data_start;
  3400.       dp->s_vaddr = data_start;
  3401.       dp->s_size = data_size;
  3402.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  3403.       dp->s_relptr = 0;
  3404.       dp->s_lnnoptr = 0;
  3405.       dp->s_nreloc = 0;
  3406.       dp->s_nlnno = 0;
  3407.       dp->s_flags = 0x40;
  3408.       strcpy (bp->s_name, ".bss");
  3409.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  3410.       bp->s_vaddr = bp->s_paddr;
  3411.       bp->s_size = bss_size;
  3412.       bp->s_scnptr = 0;
  3413.       bp->s_relptr = 0;
  3414.       bp->s_lnnoptr = 0;
  3415.       bp->s_nreloc = 0;
  3416.       bp->s_nlnno = 0;
  3417.       bp->s_flags = 0x80;
  3418.  
  3419.       coffheader.f_magic = COFF_MAGIC;
  3420.       coffheader.f_nscns = 3;
  3421.       /* store an unlikely time so programs can
  3422.        * tell that there is a bsd header
  3423.        */
  3424.       coffheader.f_timdat = 1;
  3425.       coffheader.f_symptr = 0;
  3426.       coffheader.f_nsyms = 0;
  3427.       coffheader.f_opthdr = 28;
  3428.       coffheader.f_flags = 0x103;
  3429.       /* aouthdr */
  3430.       coffheader.magic = ZMAGIC;
  3431.       coffheader.vstamp = 0;
  3432.       coffheader.tsize = tp->s_size;
  3433.       coffheader.dsize = dp->s_size;
  3434.       coffheader.bsize = bp->s_size;
  3435.       coffheader.entry = outheader.a_entry;
  3436.       coffheader.text_start = tp->s_vaddr;
  3437.       coffheader.data_start = dp->s_vaddr;
  3438.     }
  3439. #endif
  3440.  
  3441. #ifdef INITIALIZE_HEADER
  3442.   INITIALIZE_HEADER;
  3443. #endif
  3444.  
  3445.   if (strip_symbols == STRIP_ALL)
  3446.     nsyms = 0;
  3447.   else
  3448.     {
  3449.       nsyms = (defined_global_sym_count
  3450.            + undefined_global_sym_count);
  3451.       if (discard_locals == DISCARD_L)
  3452.     nsyms += non_L_local_sym_count;
  3453.       else if (discard_locals == DISCARD_NONE)
  3454.     nsyms += local_sym_count;
  3455.       /* One extra for following reference on indirects */
  3456.       if (relocatable_output)
  3457.     nsyms += set_symbol_count + global_indirect_count;
  3458.     }
  3459.  
  3460.   if (strip_symbols == STRIP_NONE)
  3461.     nsyms += debugger_sym_count;
  3462.  
  3463.   outheader.a_syms = nsyms * sizeof (struct nlist);
  3464.  
  3465.   if (relocatable_output)
  3466.     {
  3467.       outheader.a_trsize = text_reloc_size;
  3468.       outheader.a_drsize = data_reloc_size;
  3469.     }
  3470.   else
  3471.     {
  3472.       outheader.a_trsize = 0;
  3473.       outheader.a_drsize = 0;
  3474.     }
  3475.  
  3476. #ifdef COFF_ENCAPSULATE
  3477.   if (need_coff_header)
  3478.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  3479. #endif
  3480.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  3481.  
  3482.   /* Output whatever padding is required in the executable file
  3483.      between the header and the start of the text.  */
  3484.  
  3485. #ifndef COFF_ENCAPSULATE
  3486.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  3487. #endif
  3488. }
  3489.  
  3490. /* Relocate the text segment of each input file
  3491.    and write to the output file.  */
  3492.  
  3493. void
  3494. write_text ()
  3495. {
  3496.   if (trace_files)
  3497.     fprintf (stderr, "Copying and relocating text:\n\n");
  3498.  
  3499.   each_full_file (copy_text, 0);
  3500.   file_close ();
  3501.  
  3502.   if (trace_files)
  3503.     fprintf (stderr, "\n");
  3504.  
  3505.   padfile (text_pad, outdesc);
  3506. }
  3507.  
  3508. int
  3509. text_offset (entry)
  3510.      struct file_entry *entry;
  3511. {
  3512.   return entry->starting_offset + N_TXTOFF (entry->header);
  3513. }
  3514.  
  3515. /* Read in all of the relocation information */
  3516.  
  3517. void
  3518. read_relocation ()
  3519. {
  3520.   each_full_file (read_file_relocation, 0);
  3521. }
  3522.  
  3523. /* Read in the relocation sections of ENTRY if necessary */
  3524.  
  3525. void
  3526. read_file_relocation (entry)
  3527.      struct file_entry *entry;
  3528. {
  3529.   register struct relocation_info *reloc;
  3530.   int desc;
  3531.   int read_return;
  3532.  
  3533.   desc = -1;
  3534.   if (!entry->textrel)
  3535.     {
  3536.       reloc = (struct relocation_info *) xmalloc (entry->header.a_trsize);
  3537.       desc = file_open (entry);
  3538.       lseek (desc,
  3539.          text_offset (entry) + entry->header.a_text + entry->header.a_data,
  3540.          L_SET);
  3541.       if (entry->header.a_trsize != (read_return = read (desc, reloc, entry->header.a_trsize)))
  3542.     {
  3543.       fprintf (stderr, "Return from read: %d\n", read_return);
  3544.       fatal_with_file ("premature eof in text relocation of ", entry);
  3545.     }
  3546.       entry->textrel = reloc;
  3547.     }
  3548.  
  3549.   if (!entry->datarel)
  3550.     {
  3551.       reloc = (struct relocation_info *) xmalloc (entry->header.a_drsize);
  3552.       if (desc == -1) desc = file_open (entry);
  3553.       lseek (desc,
  3554.          text_offset (entry) + entry->header.a_text
  3555.          + entry->header.a_data + entry->header.a_trsize,
  3556.          L_SET);
  3557.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  3558.     fatal_with_file ("premature eof in data relocation of ", entry);
  3559.       entry->datarel = reloc;
  3560.     }
  3561. }
  3562.  
  3563. /* Read the text segment contents of ENTRY, relocate them,
  3564.    and write the result to the output file.
  3565.    If `-r', save the text relocation for later reuse.  */
  3566.  
  3567. void
  3568. copy_text (entry)
  3569.      struct file_entry *entry;
  3570. {
  3571.   register char *bytes;
  3572.   register int desc;
  3573.   register struct relocation_info *reloc;
  3574.  
  3575.   if (trace_files)
  3576.     prline_file_name (entry, stderr);
  3577.  
  3578.   desc = file_open (entry);
  3579.  
  3580.   /* Allocate space for the file's text section */
  3581.  
  3582.   bytes = (char *) alloca (entry->header.a_text);
  3583.  
  3584.   /* Deal with relocation information however is appropriate */
  3585.  
  3586.   if (entry->textrel)  reloc = entry->textrel;
  3587.   else if (relocatable_output)
  3588.     {
  3589.       read_file_relocation (entry);
  3590.       reloc = entry->textrel;
  3591.     }
  3592.   else
  3593.     {
  3594.       reloc = (struct relocation_info *) alloca (entry->header.a_trsize);
  3595.       lseek (desc, text_offset (entry) + entry->header.a_text + entry->header.a_data, 0);
  3596.       if (entry->header.a_trsize != read (desc, reloc, entry->header.a_trsize))
  3597.     fatal_with_file ("premature eof in text relocation of ", entry);
  3598.     }
  3599.  
  3600.   /* Read the text section into core.  */
  3601.  
  3602.   lseek (desc, text_offset (entry), 0);
  3603.   if (entry->header.a_text != read (desc, bytes, entry->header.a_text))
  3604.     fatal_with_file ("premature eof in text section of ", entry);
  3605.  
  3606.  
  3607.   /* Relocate the text according to the text relocation.  */
  3608.  
  3609.   perform_relocation (bytes, entry->text_start_address, entry->header.a_text,
  3610.               reloc, entry->header.a_trsize, entry);
  3611.  
  3612.   /* Write the relocated text to the output file.  */
  3613.  
  3614.   mywrite (bytes, 1, entry->header.a_text, outdesc);
  3615. }
  3616.  
  3617. /* Relocate the data segment of each input file
  3618.    and write to the output file.  */
  3619.  
  3620. void
  3621. write_data ()
  3622. {
  3623.   if (trace_files)
  3624.     fprintf (stderr, "Copying and relocating data:\n\n");
  3625.  
  3626.   each_full_file (copy_data, 0);
  3627.   file_close ();
  3628.  
  3629.   /* Write out the set element vectors.  See digest symbols for
  3630.      description of length of the set vector section.  */
  3631.  
  3632.   if (set_vector_count)
  3633.     mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  3634.          sizeof (unsigned long), outdesc);
  3635.  
  3636.   if (trace_files)
  3637.     fprintf (stderr, "\n");
  3638.  
  3639.   padfile (data_pad, outdesc);
  3640. }
  3641.  
  3642. /* Read the data segment contents of ENTRY, relocate them,
  3643.    and write the result to the output file.
  3644.    If `-r', save the data relocation for later reuse.
  3645.    See comments in `copy_text'.  */
  3646.  
  3647. void
  3648. copy_data (entry)
  3649.      struct file_entry *entry;
  3650. {
  3651.   register struct relocation_info *reloc;
  3652.   register char *bytes;
  3653.   register int desc;
  3654.  
  3655.   if (trace_files)
  3656.     prline_file_name (entry, stderr);
  3657.  
  3658.   desc = file_open (entry);
  3659.  
  3660.   bytes = (char *) alloca (entry->header.a_data);
  3661.  
  3662.   if (entry->datarel) reloc = entry->datarel;
  3663.   else if (relocatable_output)    /* Will need this again */
  3664.     {
  3665.       read_file_relocation (entry);
  3666.       reloc = entry->datarel;
  3667.     }
  3668.   else
  3669.     {
  3670.       reloc = (struct relocation_info *) alloca (entry->header.a_drsize);
  3671.       lseek (desc, text_offset (entry) + entry->header.a_text
  3672.          + entry->header.a_data + entry->header.a_trsize,
  3673.          0);
  3674.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  3675.     fatal_with_file ("premature eof in data relocation of ", entry);
  3676.     }
  3677.  
  3678.   lseek (desc, text_offset (entry) + entry->header.a_text, 0);
  3679.   if (entry->header.a_data != read (desc, bytes, entry->header.a_data))
  3680.     fatal_with_file ("premature eof in data section of ", entry);
  3681.  
  3682.   perform_relocation (bytes, entry->data_start_address - entry->header.a_text,
  3683.               entry->header.a_data, reloc, entry->header.a_drsize, entry);
  3684.  
  3685.   mywrite (bytes, 1, entry->header.a_data, outdesc);
  3686. }
  3687.  
  3688. /* Relocate ENTRY's text or data section contents.
  3689.    DATA is the address of the contents, in core.
  3690.    DATA_SIZE is the length of the contents.
  3691.    PC_RELOCATION is the difference between the address of the contents
  3692.      in the output file and its address in the input file.
  3693.    RELOC_INFO is the address of the relocation info, in core.
  3694.    RELOC_SIZE is its length in bytes.  */
  3695. /* This version is about to be severly hacked by Randy.  Hope it
  3696.    works afterwards. */
  3697. void
  3698. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  3699.      char *data;
  3700.      struct relocation_info *reloc_info;
  3701.      struct file_entry *entry;
  3702.      int pc_relocation;
  3703.      int data_size;
  3704.      int reloc_size;
  3705. {
  3706.   register struct relocation_info *p = reloc_info;
  3707.   struct relocation_info *end
  3708.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  3709.   int text_relocation = entry->text_start_address;
  3710.   int data_relocation = entry->data_start_address - entry->header.a_text;
  3711.   int bss_relocation
  3712.     = entry->bss_start_address - entry->header.a_text - entry->header.a_data;
  3713.  
  3714.   for (; p < end; p++)
  3715.     {
  3716.       register int relocation = 0;
  3717.       register int addr = RELOC_ADDRESS(p);
  3718.       register unsigned int mask = 0;
  3719.  
  3720.       if (addr >= data_size)
  3721.     fatal_with_file ("relocation address out of range in ", entry);
  3722.  
  3723.       if (RELOC_EXTERN_P(p))
  3724.     {
  3725.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  3726.       glosym *sp = ((glosym *)
  3727.             (((struct nlist *)
  3728.               (((char *)entry->symbols) + symindex))
  3729.              ->n_un.n_name));
  3730.  
  3731. #ifdef N_INDR
  3732.       /* Resolve indirection */
  3733.       if ((sp->defined & ~N_EXT) == N_INDR)
  3734.         sp = (glosym *) sp->value;
  3735. #endif
  3736.  
  3737.       if (symindex >= entry->header.a_syms)
  3738.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  3739.  
  3740.       /* If the symbol is undefined, leave it at zero.  */
  3741.       if (! sp->defined)
  3742.         relocation = 0;
  3743.       else
  3744.         relocation = sp->value;
  3745.     }
  3746.       else switch (RELOC_TYPE(p))
  3747.     {
  3748.     case N_TEXT:
  3749.     case N_TEXT | N_EXT:
  3750.       relocation = text_relocation;
  3751.       break;
  3752.  
  3753.     case N_DATA:
  3754.     case N_DATA | N_EXT:
  3755.       /* A word that points to beginning of the the data section
  3756.          initially contains not 0 but rather the "address" of that section
  3757.          in the input file, which is the length of the file's text.  */
  3758.       relocation = data_relocation;
  3759.       break;
  3760.  
  3761.     case N_BSS:
  3762.     case N_BSS | N_EXT:
  3763.       /* Similarly, an input word pointing to the beginning of the bss
  3764.          initially contains the length of text plus data of the file.  */
  3765.       relocation = bss_relocation;
  3766.       break;
  3767.  
  3768.     case N_ABS:
  3769.     case N_ABS | N_EXT:
  3770.       /* Don't know why this code would occur, but apparently it does.  */
  3771.       break;
  3772.  
  3773.     case 0:    
  3774.         error("unknown relocation code");
  3775.     break;
  3776.  
  3777.     default:
  3778.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  3779.     }
  3780.  
  3781. #ifdef RELOC_ADD_EXTRA
  3782.       relocation += RELOC_ADD_EXTRA(p);
  3783.       if (relocatable_output)
  3784.     {
  3785.       /* Non-PC relative relocations which are absolute
  3786.          or which have become non-external now have fixed
  3787.          relocations.  Set the ADD_EXTRA of this relocation
  3788.          to be the relocation we have now determined.  */
  3789.       if (! RELOC_PCREL_P (p))
  3790.         {
  3791.           if ((int)p->r_type <= RELOC_32
  3792.           || RELOC_EXTERN_P (p) == 0)
  3793.         RELOC_ADD_EXTRA (p) = relocation;
  3794.         }
  3795.       /* External PC-relative relocations continue to move around;
  3796.          update their relocations by the amount they have moved
  3797.          so far.  */
  3798.       else if (RELOC_EXTERN_P (p))
  3799.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  3800.       continue;
  3801.     }
  3802. #endif
  3803.  
  3804.       if (RELOC_PCREL_P(p))
  3805.     relocation -= pc_relocation;
  3806.  
  3807.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  3808.  
  3809.       /* Unshifted mask for relocation */
  3810.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  3811.       mask |= mask - 1;
  3812.       relocation &= mask;
  3813.  
  3814.       /* Shift everything up to where it's going to be used */
  3815.       relocation <<= RELOC_TARGET_BITPOS(p);
  3816.       mask <<= RELOC_TARGET_BITPOS(p);
  3817.  
  3818.       switch (RELOC_TARGET_SIZE(p))
  3819.     {
  3820.     case 0:
  3821.       if (RELOC_MEMORY_SUB_P(p))
  3822.         relocation -= mask & *(char *) (data + addr);
  3823.       else if (RELOC_MEMORY_ADD_P(p))
  3824.         relocation += mask & *(char *) (data + addr);
  3825.       *(char *) (data + addr) &= ~mask;
  3826.       *(char *) (data + addr) |= relocation;
  3827.       break;
  3828.  
  3829.     case 1:
  3830.       if (RELOC_MEMORY_SUB_P(p))
  3831.         relocation -= mask & *(short *) (data + addr);
  3832.       else if (RELOC_MEMORY_ADD_P(p))
  3833.         relocation += mask & *(short *) (data + addr);
  3834.       *(short *) (data + addr) &= ~mask;
  3835.       *(short *) (data + addr) |= relocation;
  3836.       break;
  3837.  
  3838.     case 2:
  3839. #ifndef _CROSS_TARGET_ARCH
  3840.       if (RELOC_MEMORY_SUB_P(p))
  3841.         relocation -= mask & *(long *) (data + addr);
  3842.       else if (RELOC_MEMORY_ADD_P(p))
  3843.         relocation += mask & *(long *) (data + addr);
  3844.       *(long *) (data + addr) &= ~mask;
  3845.       *(long *) (data + addr) |= relocation;
  3846. #else
  3847.     /* Handle long word alignment requirements of SPARC architecture */
  3848.     /* WARNING:  This fix makes an assumption on byte ordering */
  3849.     /* Marc Ullman, Stanford University    Nov. 1 1989  */
  3850.       if (RELOC_MEMORY_SUB_P(p)) {
  3851.         relocation -= mask & 
  3852.           ((*(unsigned short *) (data + addr) << 16) |
  3853.         *(unsigned short *) (data + addr + 2));
  3854.       } else if (RELOC_MEMORY_ADD_P(p)) {
  3855.         relocation += mask &
  3856.           ((*(unsigned short *) (data + addr) << 16) |
  3857.         *(unsigned short *) (data + addr + 2));
  3858.       }
  3859.       *(unsigned short *) (data + addr)     &= (~mask >> 16);
  3860.       *(unsigned short *) (data + addr + 2) &= (~mask & 0xffff);
  3861.       *(unsigned short *) (data + addr)     |= (relocation >> 16);
  3862.       *(unsigned short *) (data + addr + 2) |= (relocation & 0xffff);
  3863. #endif
  3864.       break;
  3865.  
  3866.     default:
  3867.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  3868.     }
  3869.     }
  3870. }
  3871.  
  3872. /* For relocatable_output only: write out the relocation,
  3873.    relocating the addresses-to-be-relocated.  */
  3874.  
  3875. void coptxtrel (), copdatrel ();
  3876.  
  3877. void
  3878. write_rel ()
  3879. {
  3880.   register int i;
  3881.   register int count = 0;
  3882.  
  3883.   if (trace_files)
  3884.     fprintf (stderr, "Writing text relocation:\n\n");
  3885.  
  3886.   /* Assign each global symbol a sequence number, giving the order
  3887.      in which `write_syms' will write it.
  3888.      This is so we can store the proper symbolnum fields
  3889.      in relocation entries we write.  */
  3890.  
  3891.   for (i = 0; i < TABSIZE; i++)
  3892.     {
  3893.       glosym *sp;
  3894.       for (sp = symtab[i]; sp; sp = sp->link)
  3895.     if (sp->referenced || sp->defined)
  3896.       {
  3897.         sp->def_count = count++;
  3898.         /* Leave room for the reference required by N_INDR, if
  3899.            necessary.  */
  3900.         if ((sp->defined & ~N_EXT) == N_INDR)
  3901.           count++;
  3902.       }
  3903.     }
  3904.   /* Correct, because if (relocatable_output), we will also be writing
  3905.      whatever indirect blocks we have.  */
  3906.   if (count != defined_global_sym_count
  3907.       + undefined_global_sym_count + global_indirect_count)
  3908.     fatal ("internal error");
  3909.  
  3910.   /* Write out the relocations of all files, remembered from copy_text.  */
  3911.  
  3912.   each_full_file (coptxtrel, 0);
  3913.  
  3914.   if (trace_files)
  3915.     fprintf (stderr, "\nWriting data relocation:\n\n");
  3916.  
  3917.   each_full_file (copdatrel, 0);
  3918.  
  3919.   if (trace_files)
  3920.     fprintf (stderr, "\n");
  3921. }
  3922.  
  3923. void confirm_rel(struct relocation_info *p, int i, glosym *symptr)
  3924.     {
  3925.       printf ("%3d: %3d %8x ", i, 1 << p->r_length,
  3926.           p->r_address);
  3927.  
  3928.       if (p->r_extern)
  3929.     {
  3930.       printf ("%4d %s", p->r_symbolnum, symptr->name);
  3931.     }
  3932.       else
  3933.     {
  3934.       printf ("     ");
  3935.       switch (p->r_symbolnum & ~N_EXT)
  3936.         {
  3937.         case N_TEXT:
  3938.           printf (".text ");
  3939.           break;
  3940.         case N_DATA:
  3941.           printf (".data ");
  3942.           break;
  3943.         case N_BSS:
  3944.           printf (".bss ");
  3945.           break;
  3946.         case N_ABS:
  3947.           printf (".abs ");
  3948.           break;
  3949.         default:
  3950.           printf ("base %x ", p->r_symbolnum);
  3951.           break;
  3952.         }
  3953.     }
  3954.       if (p->r_pcrel)
  3955.       printf ("PCREL ");
  3956.       printf ("\n");    
  3957.     }
  3958.     
  3959. void
  3960. coptxtrel (entry)
  3961.      struct file_entry *entry;
  3962. {
  3963.   register struct relocation_info *p, *end;
  3964.   register int reloc = entry->text_start_address;
  3965.   if (trace_files)
  3966.     prline_file_name (entry, stderr);
  3967.   p = entry->textrel;
  3968.   end = (struct relocation_info *) (entry->header.a_trsize + (char *) p);
  3969.   while (p < end)
  3970.     { glosym *symptr = 0;
  3971.       RELOC_ADDRESS(p) += reloc;
  3972.       if (RELOC_EXTERN_P(p))
  3973.     {
  3974.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  3975.       symptr = ((glosym *)
  3976.                 (((struct nlist *)
  3977.                   (((char *)entry->symbols) + symindex))
  3978.                  ->n_un.n_name));
  3979.  
  3980.       if (symindex >= entry->header.a_syms)
  3981.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  3982.  
  3983. #ifdef N_INDR
  3984.       /* Resolve indirection.  */
  3985.       if ((symptr->defined & ~N_EXT) == N_INDR)
  3986.         symptr = (glosym *) symptr->value;
  3987. #endif
  3988.  
  3989.       /* If the symbol is now defined, change the external relocation
  3990.          to an internal one.  */
  3991.  
  3992.       if (symptr->defined)
  3993.         {
  3994.           RELOC_EXTERN_P(p) = 0;
  3995.           RELOC_SYMBOL(p) = (symptr->defined & N_TYPE);
  3996. #ifdef RELOC_ADD_EXTRA
  3997.           /* If we aren't going to be adding in the value in
  3998.              memory on the next pass of the loader, then we need
  3999.          to add it in from the relocation entry.  Otherwise
  4000.              the work we did in this pass is lost.  */
  4001.           if (!RELOC_MEMORY_ADD_P(p))
  4002.         RELOC_ADD_EXTRA (p) += symptr->value;
  4003. #endif
  4004.         }
  4005.       else
  4006.         /* Debugger symbols come first, so have to start this
  4007.            after them.  */
  4008.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  4009.                  - defined_global_sym_count
  4010.                  - undefined_global_sym_count
  4011.                  - global_indirect_count);
  4012.     }
  4013.     if (trace_files) confirm_rel(p, p - entry->textrel, symptr);
  4014.       p++;
  4015.     }
  4016.   if (trace_files) fflush(stdout);
  4017.   mywrite (entry->textrel, 1, entry->header.a_trsize, outdesc);
  4018. }
  4019.  
  4020. void
  4021. copdatrel (entry)
  4022.      struct file_entry *entry;
  4023. {
  4024.   register struct relocation_info *p, *end;
  4025.   /* Relocate the address of the relocation.
  4026.      Old address is relative to start of the input file's data section.
  4027.      New address is relative to start of the output file's data section.  */
  4028.   register int reloc = entry->data_start_address - text_size;
  4029.   if (trace_files)
  4030.     prline_file_name (entry, stderr);
  4031.   p = entry->datarel;
  4032.   end = (struct relocation_info *) (entry->header.a_drsize + (char *) p);
  4033.   while (p < end)
  4034.     { glosym *symptr = 0;
  4035.       RELOC_ADDRESS(p) += reloc;
  4036.       if (RELOC_EXTERN_P(p))
  4037.     {
  4038.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  4039.       int symtype;
  4040.       symptr = ((glosym *)
  4041.                 (((struct nlist *)
  4042.                   (((char *)entry->symbols) + symindex))
  4043.                  ->n_un.n_name));
  4044.  
  4045.       if (symindex >= entry->header.a_syms)
  4046.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  4047.  
  4048. #ifdef N_INDR
  4049.       /* Resolve indirection.  */
  4050.       if ((symptr->defined & ~N_EXT) == N_INDR)
  4051.         symptr = (glosym *) symptr->value;
  4052. #endif
  4053.  
  4054.        symtype = symptr->defined & N_TYPE;
  4055.  
  4056.       if (force_common_definition
  4057.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  4058.         {
  4059.           RELOC_EXTERN_P(p) = 0;
  4060.           RELOC_SYMBOL(p) = symtype;
  4061.         }
  4062.       else
  4063.         /* Debugger symbols come first, so have to start this
  4064.            after them.  */
  4065.         RELOC_SYMBOL(p)
  4066.           = (((glosym *)
  4067.           (((struct nlist *)
  4068.             (((char *)entry->symbols) + symindex))
  4069.            ->n_un.n_name))
  4070.          ->def_count
  4071.          + nsyms - defined_global_sym_count
  4072.          - undefined_global_sym_count
  4073.          - global_indirect_count);
  4074.     }
  4075.     if (trace_files) confirm_rel(p, p - entry->datarel, symptr);
  4076.       p++;
  4077.     }
  4078.   if (trace_files) fflush(stdout);
  4079.   mywrite (entry->datarel, 1, entry->header.a_drsize, outdesc);
  4080. }
  4081.  
  4082. void write_file_syms ();
  4083. void write_string_table ();
  4084.  
  4085. /* Offsets and current lengths of symbol and string tables in output file. */
  4086.  
  4087. int symbol_table_offset;
  4088. int symbol_table_len;
  4089.  
  4090. /* Address in output file where string table starts.  */
  4091. int string_table_offset;
  4092.  
  4093. /* Offset within string table
  4094.    where the strings in `strtab_vector' should be written.  */
  4095. int string_table_len;
  4096.  
  4097. /* Total size of string table strings allocated so far,
  4098.    including strings in `strtab_vector'.  */
  4099. int strtab_size;
  4100.  
  4101. /* Vector whose elements are strings to be added to the string table.  */
  4102. char **strtab_vector;
  4103.  
  4104. /* Vector whose elements are the lengths of those strings.  */
  4105. int *strtab_lens;
  4106.  
  4107. /* Index in `strtab_vector' at which the next string will be stored.  */
  4108. int strtab_index;
  4109.  
  4110. /* Add the string NAME to the output file string table.
  4111.    Record it in `strtab_vector' to be output later.
  4112.    Return the index within the string table that this string will have.  */
  4113.  
  4114. int
  4115. assign_string_table_index (name)
  4116.      char *name;
  4117. {
  4118.   register int index = strtab_size;
  4119.   register int len = strlen (name) + 1;
  4120.  
  4121.   strtab_size += len;
  4122.   strtab_vector[strtab_index] = name;
  4123.   strtab_lens[strtab_index++] = len;
  4124.  
  4125.   return index;
  4126. }
  4127.  
  4128. /* Write the contents of `strtab_vector' into the string table.
  4129.    This is done once for each file's local&debugger symbols
  4130.    and once for the global symbols.  */
  4131.  
  4132. void
  4133. write_string_table ()
  4134. {
  4135.   register int i;
  4136.  
  4137.   lseek (outdesc, string_table_offset + string_table_len, 0);
  4138.  
  4139.   for (i = 0; i < strtab_index; i++)
  4140.     {
  4141.       mywrite (strtab_vector[i], 1, strtab_lens[i], outdesc);
  4142.       string_table_len += strtab_lens[i];
  4143.     }
  4144.  
  4145. }
  4146.  
  4147. /* Write the symbol table and string table of the output file.  */
  4148.  
  4149. void
  4150. write_syms ()
  4151. {
  4152.   /* Number of symbols written so far.  */
  4153.   int syms_written = 0;
  4154.   register int i;
  4155.   register glosym *sp;
  4156.  
  4157.   /* Buffer big enough for all the global symbols.  One
  4158.      extra struct for each indirect symbol to hold the extra reference
  4159.      following. */
  4160.   struct nlist *buf
  4161.     = (struct nlist *) alloca ((defined_global_sym_count
  4162.                 + undefined_global_sym_count
  4163.                 + global_indirect_count)
  4164.                    * sizeof (struct nlist));
  4165.   /* Pointer for storing into BUF.  */
  4166.   register struct nlist *bufp = buf;
  4167.  
  4168.   /* Size of string table includes the bytes that store the size.  */
  4169.   strtab_size = sizeof strtab_size;
  4170.  
  4171.   symbol_table_offset = N_SYMOFF (outheader);
  4172.   symbol_table_len = 0;
  4173.   string_table_offset = N_STROFF (outheader);
  4174.   string_table_len = strtab_size;
  4175.  
  4176.   if (strip_symbols == STRIP_ALL)
  4177.     return;
  4178.  
  4179.   /* Write the local symbols defined by the various files.  */
  4180.  
  4181.   each_file (write_file_syms, &syms_written);
  4182.   file_close ();
  4183.  
  4184.   /* Now write out the global symbols.  */
  4185.  
  4186.   /* Allocate two vectors that record the data to generate the string
  4187.      table from the global symbols written so far.  This must include
  4188.      extra space for the references following indirect outputs. */
  4189.  
  4190.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  4191.                      + global_indirect_count) * sizeof (char *));
  4192.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  4193.                  + global_indirect_count) * sizeof (int));
  4194.   strtab_index = 0;
  4195.  
  4196.   /* Scan the symbol hash table, bucket by bucket.  */
  4197.  
  4198.   for (i = 0; i < TABSIZE; i++)
  4199.     for (sp = symtab[i]; sp; sp = sp->link)
  4200.       {
  4201.     struct nlist nl;
  4202.  
  4203.     nl.n_other = 0;
  4204.     nl.n_desc = 0;
  4205.  
  4206.     /* Compute a `struct nlist' for the symbol.  */
  4207.  
  4208.     if (sp->defined || sp->referenced)
  4209.       {
  4210.         /* common condition needs to be before undefined condition */
  4211.         /* because unallocated commons are set undefined in */
  4212.         /* digest_symbols */
  4213.         if (sp->defined > 1) /* defined with known type */
  4214.           {
  4215.         /* If the target of an indirect symbol has been
  4216.            defined and we are outputting an executable,
  4217.            resolve the indirection; it's no longer needed */
  4218.         if (!relocatable_output
  4219.             && ((sp->defined & N_TYPE) == N_INDR)
  4220.             && (((glosym *) sp->value)->defined > 1))
  4221.           {
  4222.             glosym *newsp = (glosym *) sp->value;
  4223.             nl.n_type = newsp->defined;
  4224.             nl.n_value = newsp->value;
  4225.           }
  4226.         else
  4227.           {
  4228.             nl.n_type = sp->defined;
  4229.             if (sp->defined != (N_INDR | N_EXT))
  4230.               nl.n_value = sp->value;
  4231.             else
  4232.               nl.n_value = 0;
  4233.           }
  4234.           }
  4235.         else if (sp->max_common_size) /* defined as common but not allocated. */
  4236.           {
  4237.         /* happens only with -r and not -d */
  4238.         /* write out a common definition */
  4239.         nl.n_type = N_UNDF | N_EXT;
  4240.         nl.n_value = sp->max_common_size;
  4241.           }
  4242.         else if (!sp->defined)          /* undefined -- legit only if -r */
  4243.           {
  4244.         nl.n_type = N_UNDF | N_EXT;
  4245.         nl.n_value = 0;
  4246.           }
  4247.         else
  4248.           fatal ("internal error: %s defined in mysterious way", sp->name);
  4249.  
  4250.         /* Allocate string table space for the symbol name.  */
  4251.  
  4252.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  4253.  
  4254.         /* Output to the buffer and count it.  */
  4255.  
  4256.         *bufp++ = nl;
  4257.         syms_written++;
  4258.         if (nl.n_type == (N_INDR | N_EXT))
  4259.           {
  4260.         struct nlist xtra_ref;
  4261.         xtra_ref.n_type == N_EXT | N_UNDF;
  4262.         xtra_ref.n_un.n_strx
  4263.           = assign_string_table_index (((glosym *) sp->value)->name);
  4264.         xtra_ref.n_other = 0;
  4265.         xtra_ref.n_desc = 0;
  4266.         xtra_ref.n_value = 0;
  4267.         *bufp++ = xtra_ref;
  4268.         syms_written++;
  4269.           }
  4270.       }
  4271.       }
  4272.  
  4273.   /* Output the buffer full of `struct nlist's.  */
  4274.  
  4275.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  4276.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  4277.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  4278.  
  4279.   if (syms_written != nsyms)
  4280.     fatal ("internal error: wrong number of symbols written into output file", 0);
  4281.  
  4282.   if (symbol_table_offset + symbol_table_len != string_table_offset)
  4283.     fatal ("internal error: inconsistent symbol table length", 0);
  4284.  
  4285.   /* Now the total string table size is known, so write it.
  4286.      We are already positioned at the right place in the file.  */
  4287.  
  4288.   mywrite (&strtab_size, sizeof (int), 1, outdesc);  /* we're at right place */
  4289.  
  4290.   /* Write the strings for the global symbols.  */
  4291.  
  4292.   write_string_table ();
  4293. }
  4294.  
  4295. /* Write the local and debugger symbols of file ENTRY.
  4296.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  4297.  
  4298. /* Note that we do not combine identical names of local symbols.
  4299.    dbx or gdb would be confused if we did that.  */
  4300.  
  4301. void
  4302. write_file_syms (entry, syms_written_addr)
  4303.      struct file_entry *entry;
  4304.      int *syms_written_addr;
  4305. {
  4306.   register struct nlist *p = entry->symbols;
  4307.   register struct nlist *end = p + entry->header.a_syms / sizeof (struct nlist);
  4308.  
  4309.   /* Buffer to accumulate all the syms before writing them.
  4310.      It has one extra slot for the local symbol we generate here.  */
  4311.   struct nlist *buf
  4312.     = (struct nlist *) alloca (entry->header.a_syms + sizeof (struct nlist));
  4313.   register struct nlist *bufp = buf;
  4314.  
  4315.   /* Upper bound on number of syms to be written here.  */
  4316.   int max_syms = (entry->header.a_syms / sizeof (struct nlist)) + 1;
  4317.  
  4318.   /* Make tables that record, for each symbol, its name and its name's length.
  4319.      The elements are filled in by `assign_string_table_index'.  */
  4320.  
  4321.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  4322.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  4323.   strtab_index = 0;
  4324.  
  4325.   /* Generate a local symbol for the start of this file's text.  */
  4326.  
  4327.   if (discard_locals != DISCARD_ALL)
  4328.     {
  4329.       struct nlist nl;
  4330.  
  4331.       nl.n_type = N_TEXT;
  4332.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  4333.       nl.n_value = entry->text_start_address;
  4334.       nl.n_desc = 0;
  4335.       nl.n_other = 0;
  4336.       *bufp++ = nl;
  4337.       (*syms_written_addr)++;
  4338.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  4339.     }
  4340.  
  4341.   /* Read the file's string table.  */
  4342.  
  4343.   entry->strings = (char *) alloca (entry->string_size);
  4344.   read_entry_strings (file_open (entry), entry);
  4345.  
  4346.   for (; p < end; p++)
  4347.     {
  4348.       register int type = p->n_type;
  4349.       register int write = 0;
  4350.  
  4351.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  4352.  
  4353.  
  4354.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  4355.                 /* types of symbols are never written */
  4356.                 /* globally, though they are stored */
  4357.                 /* globally.  */
  4358.         write = relocatable_output;
  4359.       else if (!(type & (N_STAB | N_EXT)))
  4360.         /* ordinary local symbol */
  4361.     write = ((discard_locals != DISCARD_ALL)
  4362.          && !(discard_locals == DISCARD_L &&
  4363.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  4364.          && type != N_WARNING);
  4365.       else if (!(type & N_EXT))
  4366.     /* debugger symbol */
  4367.         write = (strip_symbols == STRIP_NONE);
  4368.  
  4369.       if (write)
  4370.     {
  4371.       /* If this symbol has a name,
  4372.          allocate space for it in the output string table.  */
  4373.  
  4374.       if (p->n_un.n_strx)
  4375.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  4376.                             + entry->strings);
  4377.  
  4378.       /* Output this symbol to the buffer and count it.  */
  4379.  
  4380.       *bufp++ = *p;
  4381.       (*syms_written_addr)++;
  4382.     }
  4383.     }
  4384.  
  4385.   /* All the symbols are now in BUF; write them.  */
  4386.  
  4387.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  4388.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  4389.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  4390.  
  4391.   /* Write the string-table data for the symbols just written,
  4392.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  4393.  
  4394.   write_string_table ();
  4395.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  4396. }
  4397.  
  4398. /* Copy any GDB symbol segments from the input files to the output file.
  4399.    The contents of the symbol segment is copied without change
  4400.    except that we store some information into the beginning of it.  */
  4401.  
  4402. void write_file_symseg ();
  4403.  
  4404. void
  4405. write_symsegs ()
  4406. {
  4407.   each_file (write_file_symseg, 0);
  4408. }
  4409.  
  4410. void
  4411. write_file_symseg (entry)
  4412.      struct file_entry *entry;
  4413. {
  4414.   char buffer[4096];
  4415.   struct symbol_root root;
  4416.   int indesc;
  4417.   int len;
  4418.  
  4419.   if (entry->symseg_offset == 0)
  4420.     return;
  4421.  
  4422.   /* This entry has a symbol segment.  Read the root of the segment.  */
  4423.  
  4424.   indesc = file_open (entry);
  4425.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  4426.   if (sizeof root != read (indesc, &root, sizeof root))
  4427.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  4428.  
  4429.   /* Store some relocation info into the root.  */
  4430.  
  4431.   root.ldsymoff = entry->local_syms_offset;
  4432.   root.textrel = entry->text_start_address;
  4433.   root.datarel = entry->data_start_address - entry->header.a_text;
  4434.   root.bssrel = entry->bss_start_address
  4435.     - entry->header.a_text - entry->header.a_data;
  4436.   root.databeg = entry->data_start_address - root.datarel;
  4437.   root.bssbeg = entry->bss_start_address - root.bssrel;
  4438.  
  4439.   /* Write the modified root into the output file.  */
  4440.  
  4441.   mywrite (&root, sizeof root, 1, outdesc);
  4442.  
  4443.   /* Copy the rest of the symbol segment unchanged.  */
  4444.  
  4445.   if (entry->superfile)
  4446.     {
  4447.       /* Library member: number of bytes to copy is determined
  4448.      from the member's total size.  */
  4449.  
  4450.       int total = entry->total_size - entry->symseg_offset - sizeof root;
  4451.  
  4452.       while (total > 0)
  4453.     {
  4454.       len = read (indesc, buffer, min (sizeof buffer, total));
  4455.  
  4456.       if (len != min (sizeof buffer, total))
  4457.         fatal_with_file ("premature end of file in symbol segment of ", entry);
  4458.       total -= len;
  4459.       mywrite (buffer, len, 1, outdesc);
  4460.     }
  4461.     }
  4462.   else
  4463.     {
  4464.       /* A separate file: copy until end of file.  */
  4465.  
  4466.       while (len = read (indesc, buffer, sizeof buffer))
  4467.     {
  4468.       mywrite (buffer, len, 1, outdesc);
  4469.       if (len < sizeof buffer)
  4470.         break;
  4471.     }
  4472.     }
  4473.  
  4474.   file_close ();
  4475. }
  4476.  
  4477. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  4478.  
  4479. void
  4480. symtab_init ()
  4481. {
  4482. #ifndef nounderscore
  4483.   edata_symbol = getsym ("_edata");
  4484.   etext_symbol = getsym ("_etext");
  4485.   end_symbol = getsym ("_end");
  4486. #else
  4487.   edata_symbol = getsym ("edata");
  4488.   etext_symbol = getsym ("etext");
  4489.   end_symbol = getsym ("end");
  4490. #endif
  4491.  
  4492. #ifdef sun
  4493.   {
  4494.     glosym *dynamic_symbol = getsym ("__DYNAMIC");
  4495.     dynamic_symbol->defined = N_ABS | N_EXT;
  4496.     dynamic_symbol->referenced = 1;
  4497.     dynamic_symbol->value = 0;
  4498.   }
  4499. #endif
  4500.  
  4501. #ifdef sequent
  4502.   {
  4503.     glosym *_387_flt_symbol = getsym ("_387_flt");
  4504.     _387_flt_symbol->defined = N_ABS | N_EXT;
  4505.     _387_flt_symbol->referenced = 1;
  4506.     _387_flt_symbol->value = 0;
  4507.   }
  4508. #endif
  4509.  
  4510.   edata_symbol->defined = N_DATA | N_EXT;
  4511.   etext_symbol->defined = N_TEXT | N_EXT;
  4512.   end_symbol->defined = N_BSS | N_EXT;
  4513.  
  4514.   edata_symbol->referenced = 1;
  4515.   etext_symbol->referenced = 1;
  4516.   end_symbol->referenced = 1;
  4517. }
  4518.  
  4519. /* Compute the hash code for symbol name KEY.  */
  4520.  
  4521. int
  4522. hash_string (key)
  4523.      char *key;
  4524. {
  4525.   register char *cp;
  4526.   register int k;
  4527.  
  4528.   cp = key;
  4529.   k = 0;
  4530.   while (*cp)
  4531.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  4532.  
  4533.   return k;
  4534. }
  4535.  
  4536. /* Get the symbol table entry for the global symbol named KEY.
  4537.    Create one if there is none.  */
  4538.  
  4539. glosym *
  4540. getsym (key)
  4541.      char *key;
  4542. {
  4543.   register int hashval;
  4544.   register glosym *bp;
  4545.  
  4546.   /* Determine the proper bucket.  */
  4547.  
  4548.   hashval = hash_string (key) % TABSIZE;
  4549.  
  4550.   /* Search the bucket.  */
  4551.  
  4552.   for (bp = symtab[hashval]; bp; bp = bp->link)
  4553.     if (! strcmp (key, bp->name))
  4554.       return bp;
  4555.  
  4556.   /* Nothing was found; create a new symbol table entry.  */
  4557.  
  4558.   bp = (glosym *) xmalloc (sizeof (glosym));
  4559.   bp->refs = 0;
  4560.   bp->name = (char *) xmalloc (strlen (key) + 1);
  4561.   strcpy (bp->name, key);
  4562.   bp->defined = 0;
  4563.   bp->referenced = 0;
  4564.   bp->trace = 0;
  4565.   bp->value = 0;
  4566.   bp->max_common_size = 0;
  4567.   bp->warning = 0;
  4568.   bp->undef_refs = 0;
  4569.   bp->multiply_defined = 0;
  4570.  
  4571.   /* Add the entry to the bucket.  */
  4572.  
  4573.   bp->link = symtab[hashval];
  4574.   symtab[hashval] = bp;
  4575.  
  4576.   ++num_hash_tab_syms;
  4577.  
  4578.   return bp;
  4579. }
  4580.  
  4581. /* Like `getsym' but return 0 if the symbol is not already known.  */
  4582.  
  4583. glosym *
  4584. getsym_soft (key)
  4585.      char *key;
  4586. {
  4587.   register int hashval;
  4588.   register glosym *bp;
  4589.  
  4590.   /* Determine which bucket.  */
  4591.  
  4592.   hashval = hash_string (key) % TABSIZE;
  4593.  
  4594.   /* Search the bucket.  */
  4595.  
  4596.   for (bp = symtab[hashval]; bp; bp = bp->link)
  4597.     if (! strcmp (key, bp->name))
  4598.       return bp;
  4599.  
  4600.   return 0;
  4601. }
  4602.  
  4603. /* Report a fatal error.
  4604.    STRING is a printf format string and ARG is one arg for it.  */
  4605.  
  4606. void
  4607. fatal (string, arg)
  4608.      char *string, *arg;
  4609. {
  4610.   fprintf (stderr, "ld: ");
  4611.   fprintf (stderr, string, arg);
  4612.   fprintf (stderr, "\n");
  4613.   exit (1);
  4614. }
  4615.  
  4616. /* Report a fatal error.  The error message is STRING
  4617.    followed by the filename of ENTRY.  */
  4618.  
  4619. void
  4620. fatal_with_file (string, entry)
  4621.      char *string;
  4622.      struct file_entry *entry;
  4623. {
  4624.   fprintf (stderr, "ld: ");
  4625.   fprintf (stderr, string);
  4626.   print_file_name (entry, stderr);
  4627.   fprintf (stderr, "\n");
  4628.   exit (1);
  4629. }
  4630.  
  4631. /* Report a fatal error using the message for the last failed system call,
  4632.    followed by the string NAME.  */
  4633.  
  4634. void
  4635. perror_name (name)
  4636.      char *name;
  4637. {
  4638.   extern int errno, sys_nerr;
  4639.   extern char *sys_errlist[];
  4640.   char *s;
  4641.  
  4642.   if (errno < sys_nerr)
  4643.     s = concat ("", sys_errlist[errno], " for %s");
  4644.   else
  4645.     s = "cannot open %s";
  4646.   fatal (s, name);
  4647. }
  4648.  
  4649. /* Report a fatal error using the message for the last failed system call,
  4650.    followed by the name of file ENTRY.  */
  4651.  
  4652. void
  4653. perror_file (entry)
  4654.      struct file_entry *entry;
  4655. {
  4656.   extern int errno, sys_nerr;
  4657.   extern char *sys_errlist[];
  4658.   char *s;
  4659.  
  4660.   if (errno < sys_nerr)
  4661.     s = concat ("", sys_errlist[errno], " for ");
  4662.   else
  4663.     s = "cannot open ";
  4664.   fatal_with_file (s, entry);
  4665. }
  4666.  
  4667. /* Report a nonfatal error.
  4668.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  4669.  
  4670. void
  4671. error (string, arg1, arg2, arg3)
  4672.      char *string, *arg1, *arg2, *arg3;
  4673. {
  4674.   fprintf (stderr, "%s: ", progname);
  4675.   fprintf (stderr, string, arg1, arg2, arg3);
  4676.   fprintf (stderr, "\n");
  4677. }
  4678.  
  4679.  
  4680. /* Output COUNT*ELTSIZE bytes of data at BUF
  4681.    to the descriptor DESC.  */
  4682.  
  4683. void
  4684. mywrite (buf, count, eltsize, desc)
  4685.      char *buf;
  4686.      int count;
  4687.      int eltsize;
  4688.      int desc;
  4689. {
  4690.   register int val;
  4691.   register int bytes = count * eltsize;
  4692.  
  4693.   while (bytes > 0)
  4694.     {
  4695.       val = write (desc, buf, bytes);
  4696.       if (val <= 0)
  4697.     perror_name (output_filename);
  4698.       buf += val;
  4699.       bytes -= val;
  4700.     }
  4701. }
  4702.  
  4703. /* Output PADDING zero-bytes to descriptor OUTDESC.
  4704.    PADDING may be negative; in that case, do nothing.  */
  4705.  
  4706. void
  4707. padfile (padding, outdesc)
  4708.      int padding;
  4709.      int outdesc;
  4710. {
  4711.   register char *buf;
  4712.   if (padding <= 0)
  4713.     return;
  4714.  
  4715.   buf = (char *) alloca (padding);
  4716.   bzero (buf, padding);
  4717.   mywrite (buf, padding, 1, outdesc);
  4718. }
  4719.  
  4720. /* Return a newly-allocated string
  4721.    whose contents concatenate the strings S1, S2, S3.  */
  4722.  
  4723. char *
  4724. concat (s1, s2, s3)
  4725.      char *s1, *s2, *s3;
  4726. {
  4727.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  4728.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  4729.  
  4730.   strcpy (result, s1);
  4731.   strcpy (result + len1, s2);
  4732.   strcpy (result + len1 + len2, s3);
  4733.   result[len1 + len2 + len3] = 0;
  4734.  
  4735.   return result;
  4736. }
  4737.  
  4738. /* Parse the string ARG using scanf format FORMAT, and return the result.
  4739.    If it does not parse, report fatal error
  4740.    generating the error message using format string ERROR and ARG as arg.  */
  4741.  
  4742. int
  4743. ld_parse (arg, format, error)
  4744.      char *arg, *format;
  4745. {
  4746.   int x;
  4747.   if (1 != sscanf (arg, format, &x))
  4748.     fatal (error, arg);
  4749.   return x;
  4750. }
  4751.  
  4752. #ifdef USG
  4753.  
  4754. void
  4755. bzero (p, n)
  4756.      char *p;
  4757. {
  4758.   memset (p, 0, n);
  4759. }
  4760.  
  4761. void
  4762. bcopy (from, to, n)
  4763.      char *from, *to;
  4764. {
  4765.   memcpy (to, from, n);
  4766. }
  4767.  
  4768. getpagesize ()
  4769. {
  4770.   return (4096);
  4771. }
  4772.  
  4773. #endif
  4774.  
  4775. #ifndef THINK_C
  4776. #if TARGET == SUN4
  4777.  
  4778. /* Don't use local pagesize to build for Sparc.  */
  4779.  
  4780. getpagesize ()
  4781. {
  4782.   return (8192);
  4783. }
  4784. #endif
  4785. #endif
  4786.  
  4787. int init_ld()
  4788. {
  4789. demangler = NULL;
  4790. bzero(&symtab, sizeof(symtab));
  4791. num_hash_tab_syms = 0;
  4792. local_sym_count = 0;
  4793. non_L_local_sym_count = 0;
  4794. debugger_sym_count = 0;
  4795. undefined_global_sym_count = 0;
  4796. multiple_def_count = 0;
  4797. defined_global_sym_count = 0;
  4798. common_defined_global_count = 0;
  4799. set_symbol_count = 0;
  4800. set_vector_count = 0;
  4801. set_element_prefixes = 0;
  4802. global_indirect_count = 0;
  4803. warning_count = 0;
  4804. nsyms = 0;
  4805. entry_symbol = 0;
  4806. edata_symbol = 0;   /* the symbol _edata */
  4807. etext_symbol = 0;   /* the symbol _etext */
  4808. end_symbol = 0;    /* the symbol _end */
  4809. file_table = 0;
  4810. number_of_files = 0;
  4811. input_file = 0;
  4812. input_desc = 0;
  4813. output_filename = 0;
  4814. outdesc = 0;
  4815. bzero(&outheader, sizeof(outheader));
  4816. #ifdef COFF_ENCAPSULATE
  4817. bzero(&coffheader, sizeof(coffheader));
  4818. need_coff_header = 0;
  4819. #endif
  4820. text_size = 0;        /* total size of text of all input files.  */
  4821. data_size = 0;        /* total size of data of all input files.  */
  4822. bss_size = 0;        /* total size of bss of all input files.  */
  4823. text_reloc_size = 0;    /* total size of text relocation of all input files.  */
  4824. data_reloc_size = 0;    /* total size of data relocation of all input */
  4825. set_sect_start = 0;
  4826. set_sect_size = 0;
  4827. set_vectors = 0;
  4828. text_pad = 0;
  4829. data_pad = 0;
  4830. text_start = 0;
  4831. entry_offset = 0;
  4832. data_start = 0;
  4833. text_start_alignment = 0;
  4834. T_flag_specified = 0;
  4835. Tdata_flag_specified = 0;
  4836. specified_data_size = 0;
  4837. magic = 0;
  4838. trace_files = 0;
  4839. strip_symbols = 0;
  4840. discard_locals = 0;
  4841. write_map = 0;
  4842. relocatable_output = 0;
  4843. force_common_definition = 0;
  4844. search_dirs = 0;
  4845. n_search_dirs = 0;
  4846. make_executable = 0;
  4847. force_executable = 0;
  4848. cmdline_references = 0;
  4849. cl_refs_allocated = 0;
  4850. }
  4851.  
  4852. #ifdef THINK_C
  4853. #include <Files.h>
  4854. #include <Memory.h>
  4855. #include <Resources.h>
  4856.  
  4857. makeresourcefile()
  4858.         {
  4859. #if 0
  4860.         long cnt,indesc,size;
  4861.         short fd;
  4862.         char *name;
  4863.         Handle buf;
  4864.         size = tell(outdesc);
  4865.         buf = NewHandle(size);
  4866.         if (!buf) exit(3);
  4867.         lseek(outdesc, 0, 0);
  4868.         cnt = read(outdesc, *buf, size);
  4869.         SetHandleSize(buf, cnt);
  4870.         close(outdesc);
  4871.         unlink(output_filename);
  4872.           outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC | O_RESOURCE, 0666);
  4873.           indesc = open ("/usr/lib/loader", O_RDONLY | O_RESOURCE, 0666);
  4874.           do
  4875.               {
  4876.               char buf[BUFSIZ];
  4877.               cnt = read(indesc, buf, BUFSIZ);
  4878.               if (cnt > 0)
  4879.                   {
  4880.                   write(outdesc, buf, cnt);
  4881.                   }
  4882.               }
  4883.           while (cnt);
  4884.           close(indesc);
  4885.           close(outdesc);
  4886.           chown(output_filename, '????', 'APPL');
  4887.         name = (char *)cnv_unix_name(output_filename);
  4888.         fd = OpenResFile((void *)name);
  4889.         AddResource(buf, 'UNIX', 128, "\p");
  4890.         CloseResFile(fd);
  4891. #endif
  4892.         }
  4893. #endif
  4894.